How to Add SORT functionality in REST API in Node JS

Hey there! If you're diving into the world of building REST APIs with Node.js, you might have encountered the need to implement sorting functionality. Sorting allows you to organize your data in a specific order, making it easier for users to navigate and find what they're looking for.

In this article, I'll guide you through the process of adding sorting functionality to your REST API using Node.js. You can sort from ascending to descending and high to low sorting.

So, let's see how to add sort functionality in rest API in node js, how to implement sorting in node js, how to sort data in API, sort API using node js and MongoDB, and sort in node js MongoDB.

Step 1: Setting Up Your Project

Firstly, let's create a new directory for our project and navigate into it using the terminal or command prompt:

mkdir NODE-REST-API
cd NODE-REST-API

Next, initialize a new Node.js project:

npm init -y

This command will create a package.json file with default settings.

Here, is the directory structure.

NODE-REST-API
 - controllers
 - db
 - models
 - routes
 - .env
 - app.js
 - productDB.js
 - productDB.json

 

Step 2: Installing Dependencies

We need to install the necessary packages for our project. These include Express.js for building the RESTful API and Mongoose for interacting with MongoDB. Run the following command.

npm i express
npm i nodemon
npm i mongoose
npm i dotenv

 

Step 3: Setting Up Express Server

Now, configure MongoDB and connect to the database

db/conn.js

const mongoose = require("mongoose");

const connectDB = (URI) => {
    return mongoose.connect(URI);
}

module.exports = connectDB;

.env

MONGODB_URI="Add your connection string"

 

Step 4: Creating a MongoDB Schema:

Now, let's define a schema for our data. In this example, let's assume we are creating a simple 'Products' collection.

models/products.js

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Name must be required"]
    },
    price: {
        type: Number,
        required: [true, "Price must be required"]
    },
    featured: {
        type: Boolean,
        default: false
    },
    rating: {
        type: Number,
        default: 4.5
    },
    createdAt: {
        type: Date,
        default: Date.now()
    },
    company: {
        type: String,
        enum: {
            values: ['Apple', 'Samsung', 'Dell', 'HP'],
        }
    }
});

module.exports = mongoose.model("Product", productSchema);

 

Step 5: Create a Controller

Now, we will create a products.js controller and define the function to retrieve all products.

controllers/products.js

const Product = require("../models/products");

const getAllProducts = async (req, res) => {
    const { company, name, featured, sort } = req.query;
    const queryObject = {};

    if (company) {
        queryObject.company = company;
    }

    if (name) {
        queryObject.name = {
            $regex: name, $options: "i"
        };
    }

    if(featured){
        queryObject.featured = featured;
    }

    let apiData = Product.find(queryObject);

    if(sort){
        let sortFix = sort.split(",").join(" ");
        apiData = apiData.sort(sortFix);
    }

    const products = await apiData;
    res.status(200).json({ products })
};

module.exports = getAllProducts;

Ascending and Descending order

const products = await Product.find(queryObject).sort("name"); // asc
const products = await Product.find(queryObject).sort("-name"); // desc

 

Step 6: Create a Routes

Now, we will create routes in the products.js file.

routes/products.js

const express = require('express');
const router = express.Router();
const getAllProducts = require('../controllers/products');

router.route("/").get(getAllProducts);

module.exports = router;

 

Step 7: Create an app.js file

In this step, we will create a app.js file. So, add the following code to that file.

app.js

require("dotenv").config();
const express = require('express');
const app = express();
const connectDB = require("./db/conn");

const PORT = process.env.PORT || 5000;
const product_routes = require("./routes/products");

app.get("/", (req, res) => {
    res.send("Hello");
});

app.use("/api/products", product_routes);

const start = async () => {
    try {
        await connectDB(process.env.MONGODB_URI);
        app.listen(PORT, () => {
            console.log(`${PORT} is connected`);
        });
    } catch (error) {
        console.log(error);
    }
}

start();

 

Step 8: Run Server

Now, it's time to test our API. Start your server by running:

npm run dev

output:

// ASC TO DESC with LOW TO HIGH
http://localhost:5000/api/products?sort=name,price

// ASC TO DESC with HIGH To LOW
http://localhost:5000/api/products?sort=name,-price

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS