简体   繁体   中英

Sorting and Mongoose.js findOneAndRemove

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, eg,

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?

Maybe it will help to change the condition of the sort to:

    {created_at: 1}

'or'

    {created_at: -1}

(for ascending or descending respectively). Im currently struggling with the findOneAndRemove wrapper as well. It does not seem to work flawlessly.

Based on the API Documentation here this appears to be fixed in v3.8.18 of mongoose.js .

It very likely was fixed earlier, but that's the version I'm using.

Model.findOneAndRemove({foo: 'bar'}, {sort: {created_at: -1}}, (err, 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