猫鼬/ Mongo分页

时间:2018-07-11 10:17:26

标签: javascript node.js mongodb

结合使用Express Node.JS和Mongoose,我正在尝试将分页添加到我的get请求中,但是获取消息的顺序无效。我收到了createdAt:-1 / createdAt:'desc',-createdAt的正确消息,但顺序相反。 (更改为:1或'asc'给了我最旧的消息,而那不是我所需要的)

const fetchMessages = async (req, res, chatId) => {
  try {
    const page = req.query.page || 0;
    const limit = 25;
    const take = req.query.take || limit;
    const filter = { chatId: { $eq: chatId } };

    let query = await Message.find(filter)
      .skip(take * page)
      .limit(200)
      .sort('-createdAt');

    //    query = query.sort({ createdAt: 1 });

    return res.status(200).json({ data: query });
  } catch (e) {
    console.log(e);
    return res.status(500).json({ message: e });
  }
};

解决了..

    const fetchMessages = async (req, res, chatId) => {
  try {
    // Required pagination param
    const page = req.query.page || 0;
    // Optional pagination params
    const limit = req.query.limit || 25;
    const take = req.query.take || limit;

    const filter = { chatId: { $eq: chatId } };
    let query = await Message.find(filter)
      .sort('-createdAt')
      .skip(take * page)
      .limit(limit);

    // Making newest messages come first
    query = query.reverse();

    return res.status(200).json({ data: query });
  } catch (e) {
    console.log(e);
    return res.status(500).json({ message: e })

0 个答案:

没有答案