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

相关推荐
Q_Q5110082855 分钟前
python的保险业务管理与数据分析系统
开发语言·spring boot·python·django·flask·node.js·php
shepherd1119 分钟前
批量update实现方案全面解析与最佳实践,带你掌握到底怎么批量更新最快、性能最高
后端·mysql
GoGeekBaird12 分钟前
使用GoHumanLoop拓展AI Agent人机协同边界,这次连接到飞书
人工智能·后端·github
汪子熙36 分钟前
什么是 ArkTS
后端·面试
汪子熙39 分钟前
深入解析计算机科学中的 Opaque 概念
后端
满分观察网友z1 小时前
从混乱到有序:我用“逐层扫描”法优雅搞定公司组织架构图(515. 在每个树行中找最大值)
后端·算法
风象南1 小时前
SpringBoot应用开机自启动与进程守护配置
java·spring boot·后端
寻月隐君1 小时前
Rust核心利器:枚举(Enum)与模式匹配(Match),告别空指针,写出优雅健壮的代码
后端·rust·github
满分观察网友z1 小时前
一行代码的惊人魔力:从小白到大神,我用递归思想解决了TB级数据难题(3304. 找出第 K 个字符 I)
后端·算法
程序员岳焱1 小时前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
后端·mysql·性能优化