Squirrl
Squirrl

Reputation: 4966

In mongoDB, how can I find the previous doc by _id?

I'm trying to return the previous and next mongo doc by _id. The first one below works for the next, but the latter doesn't return the previous. It returns the very first doc. I tried using $sort but it didn't seem to do anything.

    posts.findOne({'_id': {'$gt': identity}}, function(err, post) {
        "use strict";
        if (err) return callback(err, null);        
        callback(err, post);

    });

    posts.findOne({'_id': {'$lt': identity} }, {'$sort':-1}}, function(err, post) {
        "use strict";
        if (err) return callback(err, null);        
        callback(err, post);

    });

Upvotes: 1

Views: 104

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312005

That's not the right syntax for the sort option. It would be:

posts.findOne({_id: {$lt: identity}}, {sort: {_id: -1}}, function(err, post) {

Upvotes: 3

Related Questions