Use express+mongodb to implement paging query in node

introduction

In web application development, paging query is one of the essential functions. Node.js provides many excellent tools and frameworks to implement paging queries, one of the most popular frameworks is Express. At the same time, MongoDB is also a very powerful database management system, which can easily realize data storage and query. This article will introduce how to use Express and MongoDB to implement pagination query function, making your web application more flexible and efficient. Whether you are a beginner or an experienced developer, you can benefit a lot from this article.

1. Pagination case

First, you need to install through npm in the project express, mongodband mongoosethese modules.

$ npm install express mongoose

Here is a simple example of connecting and paginating queries to a MongoDB database using express and mongoose:

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;

const url = 'mongodb://localhost:27017/testdb';

mongoose.connect(url, {
    
     useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err))


const userSchema = mongoose.Schema({
    
    
  name: String,
  email: String,
});

const User = mongoose.model('User', userSchema);


app.get('/users', async (req, res) => {
    
    
  const page = parseInt(req.query.page) || 1;  // 分页数量,默认为1
  const size = parseInt(req.query.size) || 10;  // 分页大小,默认为10
  const skip = (page - 1) * size;

  const users = await User.find().skip(skip).limit(size);
  
  res.status(200).json({
    
    users});
});


app.listen(port, () => {
    
    
  console.log(`Server running at http://localhost:${
      
      port}`);
});

In this example, we first connect to the local MongoDB database through Mongoose and define a simple UserSchema. We then define a '/' route handler that paginates based on the 'page' and 'size' parameters of the query string.

app.get('/users', async (req, res) => {
    
    
  const page = parseInt(req.query.page) || 1;  // 分页数量,默认为1
  const size = parseInt(req.query.size) || 10;  // 分页大小,默认为10
  const skip = (page - 1) * size;

  const users = await User.find().skip(skip).limit(size);
  
  res.status(200).json({
    
    users});
});

This service will display the first 10 users on the first page (if they exist), the next 10 users on the second page, and so on. You can change the page by modifying the 'page' parameter in the query string, and the number of users per page by modifying the 'size' parameter.

Note: The User table here is a simulated case, it should be replaced with the actual table name in your MongoDB database in actual use.

2. Introduction to query method expansion

1. find()

find()The method MongoDBis used in to query some specified conditions and return all matching data. You can specify criteria, or find() leave blank inside to search all data in the collection.

grammar:

db.collection.find(query, projection)

in:

  • query: This is an optional parameter used to filter the required JSON documents by AND.
  • projection: This is also an optional parameter used to filter the required JSON documents by OR.

Example:
Consider a "students" collection as follows:

{
    
     "_id" : 1, "name" : "Bob", "grade" : 89 }
{
    
     "_id" : 2, "name" : "Alice", "grade" : 95 }
{
    
     "_id" : 3, "name" : "Tom", "grade" : 85 }

If we want to find all students whose grade is greater than 90 , we can use find() like this:

db.students.find( {
    
     "grade" : {
    
     $gt : 90 } } )

This will return:

{
    
     "_id" : 2, "name" : "Alice", "grade" : 95 }

You can also use the .find() method to unconditionally return all documents in a collection by omitting the query parameters, for example:

db.students.find()

This will return:

{
    
     "_id" : 1, "name" : "Bob", "grade" : 89 }
{
    
     "_id" : 2, "name" : "Alice", "grade" : 95 }
{
    
     "_id" : 3, "name" : "Tom", "grade" : 85 }

2. limit()

limit()Method used in MongoDB to limit the number of documents returned. This method can be used in conjunction with skip()the method to achieve paging effects. This method takes one parameter, the maximum number of records to return.

Here is an example of usage:

Suppose we have a orderscollection called and now we want to get the first 10 order records. Then you can use the following code:

db.orders.find().limit(10)

The above code will return ordersthe first 10 documents in the collection.

If we want to get the 11th to 20th order records, we can use skip()the method to skip the first 10 records:

db.orders.find().skip(10).limit(10)

The code above skips ordersthe first 10 documents in the collection and returns the next 10 documents. This achieves the effect of pagination.

3. skip()

skip()Method in MongoDB to skip a specified amount of data while reading it . This method is generally used together with the limit() method and is suitable for data paging scenarios.

For example, we have a user table user, and there is a requirement to display 10 users per page, now we need to get the data of the second page. Then we can use the skip() and limit() methods as follows:

db.user.find().limit(10).skip(10);

Taking the above code as an example, the purpose of calling limit(10) first is to limit the number of results returned by this search operation to no more than 10, and then the purpose of calling skip(10) is to skip the first 10 results, that is to say, from the first 11 results start to fetch . So the operation will return the 11th to 20th results, i.e. the user data corresponding to the second page in the database.

4. populate()

In MongoDB, populate()method is used to get details of referenced fields of a document. In other words, it is used to replace the field of the referenced document.

Examples are as follows:

Suppose you have two MongoDB models, one is User and the other is Post. Each user in the User model may have multiple posts.

The User model is defined as follows:

const userSchema = mongoose.Schema({
    
    
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  posts: [{
    
     type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});

module.exports = mongoose.model('User', userSchema);

The Post model is defined as follows:

const postSchema = mongoose.Schema({
    
    
  _id: mongoose.Schema.Types.ObjectId,
  title: String,
  content: String
});

module.exports = mongoose.model('Post', postSchema);

As we can see above, there is a field in the User model posts, which is an array containing some Posts _id. So, if we want to get detailed information about a user and all of his articles, we need to use populate()this method.

User
.findOne({
    
     name: 'John' })
.populate('posts') // 该方法替换了 `posts` 字段里的所有 Post Id 为具体的 Post 对象。
.exec((err, user) => {
    
    
  console.log("User: ", user);  // 显示用户以及该用户的所有文章对象
});

This is populate()the usage of . In practical applications, this method is often used in the scene of obtaining associated data, which is very convenient and the code is clear.

Notice: In Mongoose, populate()only works on fields of type ObjectIds. At the same time, the referenced model needs to be correctly defined and exported, otherwise populate()the corresponding model will not be found and will fail.

Summarize

To sum up, in this blog, we discussed in detail how to use express and mongodb in node.js to implement paging queries. We first introduced the basics of express and mongodb, and then we discussed in depth how to combine the two to achieve data acquisition and paging display. Although the implementation process may be somewhat complicated, as long as you follow the steps and fully understand the meaning of each step, you can successfully implement this function. This not only improves our node.js development efficiency, but also makes our applications more user-friendly. Later, we will discuss more about the application of node.js and related technologies, so stay tuned.

Guess you like

Origin blog.csdn.net/jieyucx/article/details/132147043