简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM