如何使用排序 ID 在 Node.js 中进行分页?
NodeJS 中的分页定义为添加数字以标识页面的序号。在分页中,当数据库中的数据非常大时,我们习惯于跳过和限制以减少数据的大小。在本文中,我们将在 NodeJS 中使用排序 ID 进行分页。
方法:在 NodeJS 中排序有助于按升序或降序对结果进行排序。我们使用 sort() 方法,在该方法中我们传递一个导致升序或降序的参数。使用值-1 在排序对象中以降序排序和1 按升序对对象进行排序。
安装模块:您可以使用以下命令安装所需的模块。
npm install mongoose
npm install express
npm install bcryptjs
npm install body-parser
项目结构:它看起来像这样。
MongoDB 数据库:以下是本示例存储在您的数据库中的示例数据。
方法一:使用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");
});
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");
});
应用程序.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 ,您将看到以下输出:
方法2:使用ID降序排序
用户.js
var mongoose = require("mongoose");
var userSchema = new mongoose.Schema({
username:String,
password:String
});
module.exports = mongoose.model("User", userSchema);
应用程序.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 ,您将看到以下输出: