【问题标题】:How to use sort in find query using mongoose如何在使用猫鼬的查找查询中使用排序
【发布时间】:2021-09-11 02:21:55
【问题描述】:
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 在猫鼬中实现基于光标的分页

【问题讨论】:

    标签: sql database mongodb mongoose pagination


    【解决方案1】:

    对于猫鼬的分页,喜欢这样:

    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" });
      }
    

    【讨论】:

    • 这使用了跳过和限制..但我在这里尝试实现基于光标的分页
    猜你喜欢
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多