Express + MongoDB 实现列表分页查询

使用 `find` 方法查询数据,结合 `skip` 和 `limit` 方法实现分页效果

// 分页查询路由

app.get("/users", async (req, res) => {

  try {

    // 获取页码和每页数量,默认为第 1 页,每页 10 条记录

    const page = parseInt(req.query.page) || 1;

    const limit = parseInt(req.query.limit) || 10;

    // 计算跳过的记录数

    const skip = (page - 1) * limit;

    // 查询指定页的数据

    const users = await User.find().skip(skip).limit(limit);

    // 统计总记录数

    const total = await User.countDocuments();

    // 计算总页数

    const totalPages = Math.ceil(total / limit);

    res.json({

      page,

      limit,

      total,

      totalPages,

      data: users,

    });

  } catch (error) {

    console.error("Error fetching users:", error);

    res.status(500).json({ error: "Internal Server Error" });

  }

});

你可能感兴趣的:(express,mongodb,数据库)