2分钟学会在Node项目中实现分页功能!一看就会!

1. 分页 SQL

在 MySQL 中分页查询的 sql 语句是这样的:

css 复制代码
SELECT * FROM `users` 
LIMIT offset, pageSize;

其中最关键的偏移量: const offset = (current - 1) * pageSize

  • current 当前页
  • pageSize 每页显示的个数

2. sequelize 分页方法

sequelize 的分页方法是 findAndCountAll(condition)

其中参数 condition:

css 复制代码
const condition = {
    order: [['id', 'DESC']], // 按照id倒叙
    limit: pageSize,
    offset: offset
  }

condition 中还可以添加过滤条件,例如:模糊查询

css 复制代码
 const condition = {
      order: [['id', 'DESC']], // 按照id倒叙
      limit: pageSize,
      offset: offset,
      where:{
       name: {
          [Op.like]: `%${query.name}%`
        }
      }
    }

完整代码:

css 复制代码
const express = require('express');
const router = express.Router();
const User = require("../models/user.js")
const { Op } = require('sequelize');

// 获取用户分页信息
router.get('/page', async (req, res) => {
  try {
    const query = req.query;
    // 当前页
    const current = Number(query.current) || 1
    // 每页个数
    const pageSize = Number(query.pageSize) || 10
    // 偏移
    const offset = (current - 1) * pageSize
    // 条件
    const condition = {
      order: [['id', 'DESC']], // 按照id倒叙
      limit: pageSize,
      offset: offset
    }
    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`
        }
      }
    }
    // 分页查询
    const { count, rows } = await User.findAndCountAll(condition);
    // 封装查询数据
    const data = {
      rows,
      pagination: {
        total: count,
        current,
        pageSize
      }
    }
    // 返回
    res.status(200).json({
          code: 200,
          message: "查询成功",
          data
        });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;

3.测试

相关推荐
ldj202011 分钟前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿12 分钟前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
江南一点雨20 分钟前
Tokenizer 和 BPE
后端
风象南24 分钟前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端
洛阳泰山25 分钟前
Spring Boot 整合 Nacos 实战教程:服务注册发现与配置中心详解
java·spring boot·后端·nacos
江南一点雨38 分钟前
ChatGPT与最大似然估计
后端
程序员爱钓鱼2 小时前
Go语言实战案例-判断一个数是否为质数
后端·google·go
程序员爱钓鱼2 小时前
Go语言实战案例-读取本地文本文件内容
后端·google·go
mCell10 小时前
Go 并发编程基础:从 Goroutine 到 Worker Pool 实践
后端·性能优化·go
Python智慧行囊10 小时前
Flask 框架(一):核心特性与基础配置
后端·python·flask