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.测试

相关推荐
朝朝暮暮an3 小时前
Day 2|Node.js 运行机制、模块系统与异步初探
node.js
索荣荣5 小时前
Java Session 全面指南:原理、应用与实践(含 Spring Boot 实战)
java·spring boot·后端
千寻技术帮6 小时前
10333_基于SpringBoot的家电进存销系统
java·spring boot·后端·源码·项目·家电进存销
dear_bi_MyOnly6 小时前
【多线程——线程状态与安全】
java·开发语言·数据结构·后端·中间件·java-ee·intellij-idea
小信丶8 小时前
@EnableTransactionManagement注解介绍、应用场景和示例代码
java·spring boot·后端
To Be Clean Coder8 小时前
【Spring源码】createBean如何寻找构造器(四)——类型转换与匹配权重
java·后端·spring
-孤存-8 小时前
SpringBoot核心注解与配置详解
java·spring boot·后端
2301_818732069 小时前
项目启动报错,错误指向xml 已解决
xml·java·数据库·后端·springboot
小王不爱笑13210 小时前
SpringBoot 整合 Ollama + 本地 DeepSeek 模型
java·spring boot·后端
aidou131410 小时前
Visual Studio Code(VS Code)安装步骤
vscode·npm·node.js·环境变量