Reputation: 13
I currently have the following query to return the count
most recently updated posts for a given status
.
var query = Post.find()
.where('status').equals(status)
.sort('-updated')
.limit(count);
If status
was 'approved' and count
was 3 then my result would look like this:
[
{
"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",
}
]
I need to be able to specify an id
to offset my results by.
For example if status
was 'approved', count
was 2 and the offset id was 'test1' the result should be:
[
{
"id": "test2",
"updated": "2015-11-30T16:51:52.125Z",
"status": "approved",
},
{
"id": "test3",
"updated": "2015-11-30T16:51:50.469Z",
"status": "approved",
}
]
So I'm ordering by the updated property but results should only start from the document after the offset id.
Upvotes: 1
Views: 803
Reputation: 13682
You cannot offset by a specific id but you can skip a certain number of documents by using 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
If you want to skip all documents before and including a specific id, you'll have to do it manually (I can post code if it's what you need).
Edit
To skip all documents until you reach a specific document:
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);
});
});
Upvotes: 0
Reputation: 14590
I would like to exclude the id you don't need to skip them, there isn't any other solution:
var query = Post.find({
$and: [{
status: status
}, {
id: {
$nin: ['test1']
}
}]
})
.sort('-updated')
.limit(count);
With $nin
you can exclude multiple id
by using an array of ids like this: ['test1', 'test2', 'etc...']
Upvotes: 1