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

相关推荐
yuuki23323321 小时前
【数据结构】用顺序表实现通讯录
c语言·数据结构·后端
你的人类朋友21 小时前
【Node】手动归还主线程控制权:解决 Node.js 阻塞的一个思路
前端·后端·node.js
史不了1 天前
静态交叉编译rust程序
开发语言·后端·rust
码事漫谈1 天前
C++中的多态:动态多态与静态多态详解
后端
码事漫谈1 天前
单链表反转:从基础到进阶的完整指南
后端
与遨游于天地1 天前
Spring解决循环依赖实际就是用了个递归
java·后端·spring
cdming1 天前
Node.js 解释环境变量的定义、作用及在Node.js中的重要性,区分开发、测试、生产环境配置需求。
node.js
Python私教1 天前
用 FastAPI + Pydantic 打造“可验证、可热载、可覆盖”的配置中心
后端
Python私教1 天前
FastAPI “零手工”路由:自动扫描模块、自动注册路由的工程级实践
后端