How to offset a Mongoose sort query to start after a specific document

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.

Answers


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...']


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);
    });
});

Need Your Help

Centering menu bar with CSS

html css menu center

I have two problems with my menu bar. What I want to achieve is to center the links on the header (including the logo picture) and have exactly the same height for the header as the menu. When I ad...

NodeJS/Express Workflow with CoffeeScript & Stylus

node.js coffeescript express stylus

I have decided to use ExpressJS with CoffeeScript and Stylus. Usually when I work with CoffeeScript, I do a coffee --watch and something similar for Compass/SASS. Here, since CoffeeScript and Stylu...