如何偏移Mongoosesorting查询以在特定文档之后启动
我目前有以下查询返回给定status
最近更新的postcount
。
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", } ]
所以我按更新的属性sorting,但结果应该只从偏移ID之后的文档开始。
我想排除你不需要跳过他们的ID,没有任何其他的解决scheme:
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,你必须手动(我可以发布代码,如果是你所需要的)。
编辑
要跳过所有文档,直到您到达特定文档:
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); }); });