如何使用猫鼬在查找查询中使用排序

时间:2021-06-28 19:34:29

标签: sql database mongodb mongoose pagination

With this_set AS (
    SELECT * FROM users
    WHERE last_name < ‘Diggory’ 
    ORDER BY last_name 
    DESC LIMIT 5
)
SELECT * FROM this_set ORDER BY last_name ASC

我想在猫鼬中实现同样的目标..我试过了

 records = await model
.find({...filter, deleted:null })
.select('-deleted -__v')
.where(paginationParams) // {last_name < 'Diggory' } here i want to apply sort last_name by desc like {last_name : -1}
.sort({last_name : 1}) // asc order
.limit(pageLimit + 1)
.exec()

引用网址:https://medium.com/swlh/how-to-implement-cursor-pagination-like-a-pro-513140b65f32

在这里,我正在尝试使用下一个和上一个 ulr 在 mongoose 中实现基于光标的分页

1 个答案:

答案 0 :(得分:0)

对于 mongoose 中的分页,像这样:

let page = req.query.page ? parseInt(req.query.page) : 1;
let limit = req.query.limit ? parseInt(req.query.limit) : 5;

  try {
    const collection= await Collection.find(
    { filters }
  )
    .skip(limit * page - limit)
    .sort([["createdAt", "desc"]])
    .limit(limit)
    .exec();
    if (!collection) {
      return res.status(400).json({ error: 'None...' });
    }
    res.json({
      collection,
      current: page,
      pages: Math.ceil(count / limit),
      count,
  });
  } catch (error) {
    return res.status(500).json({ error: "Server error" });
  }