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

相关推荐
易安说AI40 分钟前
Claude Opus 4.6 凌晨发布,我体验了一整晚,说说真实感受。
后端
易安说AI42 分钟前
Ralph Loop 让Claude无止尽干活的牛马...
前端·后端
易安说AI1 小时前
用 Claude Code 远程分析生产日志,追踪 Claude Max 账户被封原因
后端
颜酱2 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
Coder_Boy_4 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
掘金者阿豪5 小时前
关系数据库迁移的“暗礁”:金仓数据库如何规避数据完整性与一致性风险
后端
ServBay6 小时前
一个下午,一台电脑,终结你 90% 的 Symfony 重复劳动
后端·php·symfony
sino爱学习6 小时前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端
颜酱6 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
掘金者阿豪6 小时前
UUID的隐形成本:一个让数据库“慢下来”的陷阱
后端