[英]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.