Sorting in ascending order using IDs

JavaScript
// user.js

let mongoose = require("mongoose");

let userSchema = new mongoose.Schema({
    username:String,
    password:String
});

module.exports = mongoose.model("User",userSchema);
JavaScript
// app.js

const express = require('express'),
    Mongoose = require('mongoose'),
    Bcrypt = require('bcryptjs'),
    bodyParser = require('body-parser'),
    jsonParser = bodyParser.json(),
    User = require('./user')

const app = express();

const db = `mongodb+srv://pallavi:pallavi123@
cluster0.k0sop.mongodb.net/user?retryWrites=
true&w=majority`

Mongoose.connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
}).then(() => console.log('MongoDB Connected....'))

// Handling GET /send Request
app.get("/send", async (req, res, next) => {

    try {
        let { page, size, sort } = req.query;

        // If the page is not applied in query.
        if (!page) {

            // Make the Default value one.
            page = 1;
        }

        if (!size) {
            size = 10;
        }

        //  We have to make it integer because
        // query parameter passed is string
        const limit = parseInt(size);

        // We pass 1 for sorting data in 
        // ascending order using ids
        const user = await User.find().sort(
            { votes: 1, _id: 1 }).limit(limit)
        res.send({
            page,
            size,
            Info: user,
        });
    }
    catch (error) {
        res.sendStatus(500);
    }
});

// Handling POST /send Request
app.post('/send', jsonParser, (req, res) => {

    req.body.password = 
        Bcrypt.hashSync(req.body.password, 10);
    var newUser = new User({
        username: req.body.username,
        password: req.body.password,

    })

    newUser.save()
        .then(result => {
            console.log(result);
        });
})

// Server setup
app.listen(3000, function () {
    console.log("Express Started on Port 3000");
});

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:

How to do Pagination in Node.js using Sorting Ids ?

Implementing pagination in a Node.js application involves fetching and displaying data in chunks or pages, typically from a database. One common approach to pagination is using sorting IDs, where each record in the dataset is assigned a unique identifier (ID) that determines its position in the sorted sequence. This method allows you to efficiently retrieve data based on these IDs to implement pagination. Let’s dive into how you can achieve pagination using sorting IDs in a Node.js application.

Similar Reads

Approach

Sorting in the NodeJS helps to sort the results in ascending or descending order. We use the sort() method in which we pass one parameter that results in ascending or descending order. Use the value -1 in the sort object to sort descending and 1 to sort the object in the ascending order....

Steps to Setup the Project

Step 1: Create a nodeJS folder by using this command...

Sorting in ascending order using IDs

JavaScript // user.js let mongoose = require("mongoose"); let userSchema = new mongoose.Schema({ username:String, password:String }); module.exports = mongoose.model("User",userSchema); JavaScript // app.js const express = require('express'), Mongoose = require('mongoose'), Bcrypt = require('bcryptjs'), bodyParser = require('body-parser'), jsonParser = bodyParser.json(), User = require('./user') const app = express(); const db = `mongodb+srv://pallavi:pallavi123@ cluster0.k0sop.mongodb.net/user?retryWrites= true&w=majority` Mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }).then(() => console.log('MongoDB Connected....')) // Handling GET /send Request app.get("/send", async (req, res, next) => { try { let { page, size, sort } = req.query; // If the page is not applied in query. if (!page) { // Make the Default value one. page = 1; } if (!size) { size = 10; } // We have to make it integer because // query parameter passed is string const limit = parseInt(size); // We pass 1 for sorting data in // ascending order using ids const user = await User.find().sort( { votes: 1, _id: 1 }).limit(limit) res.send({ page, size, Info: user, }); } catch (error) { res.sendStatus(500); } }); // Handling POST /send Request app.post('/send', jsonParser, (req, res) => { req.body.password = Bcrypt.hashSync(req.body.password, 10); var newUser = new User({ username: req.body.username, password: req.body.password, }) newUser.save() .then(result => { console.log(result); }); }) // Server setup app.listen(3000, function () { console.log("Express Started on Port 3000"); });...

Sorting in descending order using IDs

JavaScript // user.js let mongoose = require("mongoose"); let userSchema = new mongoose.Schema({ username:String, password:String }); module.exports = mongoose.model("User", userSchema); JavaScript // app.js let express = require('express'), Mongoose = require('mongoose'), Bcrypt = require('bcryptjs'), bodyParser = require('body-parser'), jsonParser = bodyParser.json(), User = require('./user') const app = express(); const db = `mongodb+srv://pallavi:pallavi123 @cluster0.k0sop.mongodb.net/user? retryWrites=true&w=majority` Mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }).then(() => console.log('MongoDB Connected....')) // Handling GET /send Request app.get("/send", async (req, res, next) => { try { let { page, size, sort } = req.query; // If the page is not applied in query if (!page) { // Make the Default value one page = 1; } if (!size) { size = 10; } // We have to make it integer because // the query parameter passed is string const limit = parseInt(size); // We pass 1 for sorting data in // descending order using ids const user = await User.find().sort( { votes: 1, _id: -1 }).limit(limit) res.send({ page, size, Info: user, }); } catch (error) { res.sendStatus(500); } }); // Handling POST /send Request app.post('/send', jsonParser, (req, res) => { req.body.password = Bcrypt.hashSync(req.body.password, 10); let newUser = new User({ username: req.body.username, password: req.body.password, }) newUser. save() .then(result => { console.log(result); }); }) // Server setup app.listen(3000, function () { console.log("Express Started on Port 3000"); });...

Contact Us