如何使用排序ID在Node.js中进行分页

如何使用排序ID在Node.js中进行分页

在NodeJS中,分页被定义为添加数字来标识页面的顺序编号。在分页中,我们通常使用跳过和限制来减少数据库中数据的大小,当它们的数量非常大时。在本文中,我们将使用排序ID在NodeJS中进行分页。

方法: 在NodeJS中进行排序可以帮助对结果按升序或降序排序。我们使用sort()方法,在其中传递一个参数以得到升序或降序的结果。在排序对象中,使用值 -1 来进行降序排序,使用值 1来进行升序排序。

安装模块: 您可以使用以下命令安装所需的模块。

npm install mongoose 
npm install express 
npm install bcryptjs 
npm install body-parser

项目结构: 看起来会像这样。

如何使用排序ID在Node.js中进行分页

MongoDB 数据库:

以下是在您的数据库中存储的示例数据,供本示例使用。

如何使用排序ID在Node.js中进行分页

方法1: 使用ID升序排序。

user.js

var mongoose = require("mongoose"); 
  
var userSchema = new mongoose.Schema({ 
    username:String, 
    password:String 
}); 
  
module.exports = mongoose.model("User",userSchema);

app.js

var 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"); 
}); 

运行 app.js 文件,使用以下命令:

node app.js

输出: 现在打开您的浏览器并转到 http://localhost:3000/send?sort ,您将看到以下输出:

如何使用排序ID在Node.js中进行分页

方法2:使用IDs按降序排序

user.js

var mongoose = require("mongoose"); 
  
var userSchema = new mongoose.Schema({ 
    username:String, 
    password:String 
}); 
  
module.exports = mongoose.model("User", userSchema);

app.js

var 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); 
          
    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"); 
}); 

运行 app.js 文件,使用以下命令:

node app.js

输出: 现在打开您的浏览器并转到 http://localhost:3000/send?sort ,你将会看到以下的输出:

如何使用排序ID在Node.js中进行分页

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程