Sling Academy
Home/Node.js/Mongoose: Sorting products by price (ASC and DESC)

Mongoose: Sorting products by price (ASC and DESC)

Last updated: December 30, 2023

Introduction

Sorting queries by specific criteria is a fundamental feature in many database-driven applications. With Mongoose, the widely used Object Data Modeling (ODM) library for MongoDB and Node.js, sorting data becomes a breeze. In this guide, we will delve into how to sort products by price in both ascending (ASC) and descending (DESC) order using Mongoose. We’ll start with the basics and gradually explore more sophisticated sorting techniques, including dynamic sorting based on user input and compound sorting strategies.

To follow along, you should have a basic understanding of Node.js, JavaScript or TypeScript, and MongoDB. We’ll use modern syntax and features such as ES modules, arrow functions, and async/await to make the code clean and easy to follow.

Basic Sorting Examples

Basic sort in ascending order:
Sorting products by price in ascending order can be as simple as adding a .sort() clause to your Mongoose query. Here’s a basic example:

const mongoose = require('mongoose');
const Product = mongoose.model('Product', { name: String, price: Number });

const getProductsAscending = async () => {
  try {
    const products = await Product.find().sort({ price: 1 }).exec();
    console.log(products);
  } catch (err) {
    console.error(err);
  }
};

getProductsAscending();

Here, the argument { price: 1 } passed to the .sort() method indicates that we want the results sorted by the price property in ascending order. The number 1 signifies ‘ascending’, while a -1 would signify ‘descending’. We use async/await to ensure we’re handling the promise returned by the exec() method, and catch any potential errors in the process.

Basic sort in descending order:
For descending order, simply flip the sort value:

const getProductsDescending = async () => {
  try {
   const products = await Product.find().sort({ price: -1 }).exec();
   console.log(products);
  } catch (err) {
   console.error(err);
  }
};

getProductsDescending();

Dynamic Sorting

In real-world applications, the sorting order is often determined at runtime based on user input. To implement dynamic sorting, we can pass a variable specifying sort direction to our function:

const getProductsSorted = async (sortOrder) => {
  try {
   const sortOption = sortOrder === 'asc' ? 1 : -1;
   const products = await Product.find().sort({ price: sortOption }).exec();
   console.log(products);
  } catch (err) {
   console.error(err);
  }
};

// Usage
getProductsSorted('asc');  // For ascending
getProductsSorted('desc'); // For descending

Advanced Sorting Techniques

In more complex scenarios, you might want to sort based on multiple criteria. Mongoose allows you to specify multiple fields and their respective directions in the .sort() method. For example, imagine you want to first sort the products by price and then by their name alphabetically. Here’s how you could do it:

const mongoose = require('mongoose');
const Product = mongoose.model('Product', { name: String, price: Number });

const getProductsAdvancedSorting = async () => {
  try {
   const products = await Product.find()
   .sort({ price: 1, name: 1 })
   .exec();
   console.log(products);
  } catch (err) {
   console.error(err);
  }
};

getProductsAdvancedSorting();

This query will first sort by price in ascending order and then by name, also in ascending order. This approach can be tailored based on your requirements to sort by any field and direction.

Final Words

In this guide, we’ve explored several methods to sort products by price using Mongoose, from the most basic to the more complex. Sorting is an essential aspect of building intuitive and user-friendly interfaces. By mastering these quick, flexible sorting techniques in Mongoose, you can significantly improve data presentation and enhance user experience.

While we’ve covered sorting by price, remember that these strategies can easily be repurposed to sort by any other criteria within your data models, empowering you to build more dynamic and interactive applications.

Next Article: Fixing Mongoose Error: Missing ‘cursor’ Option

Previous Article: Mongoose: Reference a schema in another schema (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates