Sorting and Mongoose.js findOneAndRemove

Viewed 3885

According to the Mongoose.js docs, it should be possible to add a sort directive to methods passed directly to the database like findOneAndUpdate or findOneAndRemove.

I'm trying to grab a single document that matches a criterion and remove it from the database. So far, I have tried:

Model.findOneAndRemove({foo: 'bar'})
    .sort({created_at: 'asc'})
    .exec(callback);

and

Model.findOneAndRemove({foo: 'bar'}, {sort: {created_at: 'asc'}}).exec(callback);

Both of which seem to ignore the sort instruction and simply find and remove the most recently added matching document, not the document with the earliest created_at date.

Issuing the query as a findOne and then removing the document in the callback function works as expected, e.g.,

Model.findOne({foo: 'bar'}).sort({created_at: 'asc'})
    .exec(function (err, doc) { 
        doc.remove(); 
    });

returns and removes the document with the earliest created_at date, so I believe that sorting in findOneAndRemove queries (which, unlike regular queries, are handed directly to MongoDB) must use a different syntax.

Using findOne instead of findOneAndRemove is a viable option, but I would prefer that the operation be atomic if at all possible.

Is it possible to use sort directives with Mongoose.js queries like findOneAndUpdate or findOneAndRemove, and, if so, what syntax is used?

2 Answers
Related