[英]How to offset a Mongoose sort query to start after a specific document
我目前有以下查询可返回给定status
最新更新帖子count
。
var query = Post.find()
.where('status').equals(status)
.sort('-updated')
.limit(count);
如果status
为“已批准”且count
为3,则我的结果将如下所示:
[
{
"id": "test1",
"updated": "2015-11-30T16:51:54.988Z",
"status": "approved",
},
{
"id": "test2",
"updated": "2015-11-30T16:51:52.125Z",
"status": "approved",
},
{
"id": "test3",
"updated": "2015-11-30T16:51:50.469Z",
"status": "approved",
}
]
我需要能够指定一个id
来抵消我的结果。
例如,如果status
为“已批准”, count
为2,偏移ID为“ test1”,则结果应为:
[
{
"id": "test2",
"updated": "2015-11-30T16:51:52.125Z",
"status": "approved",
},
{
"id": "test3",
"updated": "2015-11-30T16:51:50.469Z",
"status": "approved",
}
]
因此,我按更新的属性排序,但结果应仅从偏移量ID之后的文档开始。
我想排除您不需要跳过它们的ID,没有其他解决方案:
var query = Post.find({
$and: [{
status: status
}, {
id: {
$nin: ['test1']
}
}]
})
.sort('-updated')
.limit(count);
使用$nin
您可以通过使用如下所示的ID数组来排除多个id
: ['test1', 'test2', 'etc...']
您不能使用特定的ID进行偏移,但是可以使用skip()
一定数量的文档。
var query = Post.find()
.where('status').equals(status)
.sort('-updated')
.limit(count)
.skip(1); // <<< put the number of docs you want to skip here
如果您想跳过所有文档(包括一个特定的ID)并在其中包含一个特定的ID,则必须手动进行(如果需要,我可以发布代码)。
编辑
要跳过所有文档,直到找到特定文档:
var query = Post.find()
.where('status').equals(status)
.sort('-updated')
.limit(count);
var offsetId = 'test1';
var filteredDocs = [];
query.exec().then(function (docs) {
var skipped = true;
docs.forEach(function (doc) {
if (skipped && doc.id == offsetId) skipped = false;
if (!skipped) filteredDocs.push(doc);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.