node.js - Mongoose 中的过滤、排序和分页返回重复值

标签 node.js mongodb express mongoose

我在 mongodb 中有一个产品文档。我在过滤和排序后使用 skiplimit 通过分页检索数据,就像这样使用 mongoose -

Product.find({gender:'male'})
  .sort(price: 1)
  .skip(page * 25).limit(25);

当页面值为 0 时,它按预期返回结果,但是当页面值更改为 1 时,它返回页面值为 0 时已经检索到的一些结果。我正在传递所有这些参数通过 nodjs express 中的查询。在使用 mongoose 分页时,如何仅通过排序和过滤检索唯一值?

最佳答案

如前所述here :

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.

If consistent sort order is desired, include at least one field in your sort that contains unique values. The easiest way to guarantee this is to include the _id field in your sort query.

所以你可以通过以下方式解决问题:

Product.find({gender:'male'})
  .sort({price: 1, _id: 1})
  .skip(page * 25).limit(25);

关于node.js - Mongoose 中的过滤、排序和分页返回重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68246123/

相关文章:

javascript - 将 MongoDB 中的用户的对象转换为数组

javascript - Express文件上传内存问题

node.js - 关闭连接而不是设置 'keep-alive'

javascript - Node 环境和浏览器中的等效 GET 请求未显示相同的结果

mongodb - 如何自定义 MongoRepository 而不覆盖接口(interface)中带注释的 @Query 方法?

php - 如何在mongodb中对查找结果进行排序

mysql - 日期范围之间的 Sequelize 始终返回今天的日期而不是记录中的日期

javascript - 尝试 babel JavaScript 或 TypeScript 文件以在 Node 环境中使用

javascript - AdonisJs 中的 not_required_when 验证器

javascript - 为什么 JavaScript 中的 parseInt 和 isNaN 行为不一致?