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

相关推荐
tERS ERTS11 分钟前
node.js下载、安装、设置国内镜像源(永久)(Windows11)
node.js
dovens36 分钟前
SpringBoot集成MQTT客户端
java·spring boot·后端
❀͜͡傀儡师41 分钟前
Spring Boot 集成 RocksDB 实战:打造高性能 KV 存储加速层
java·spring boot·后端·rocksdb
TeamDev1 小时前
如何在 DotNetBrowser 中使用本地 AI 模型
前端·后端·.net
Rust语言中文社区1 小时前
【Rust日报】2026-05-02 Temper - 用 Rust 编写的 Minecraft 服务器项目发布 0.1.0 版
运维·服务器·开发语言·后端·rust
陈随易1 小时前
2年没用Nodejs了,Bun很香
前端·后端·程序员
donecoding2 小时前
Corepack 完全解析:从懵到懂,包管理器自由了
前端·node.js·前端工程化
用户9416146933652 小时前
Python 实时监控 A 股行情并自动筛选强势股(REST + WebSocket 两种方案)
后端·数据分析
Java编程爱好者2 小时前
吃透 ForkJoinPool:工作窃取底层原理,一次性讲透
后端