我在 mongodb 中有一个产品文档。我在过滤和排序后使用 skip 和 limit 通过分页检索数据,就像这样使用 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/