Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose findOne with sorting

I have a problem with a mongo request:

models.user.findOne(
    {},
    {
        sort: {
            date_register: -1
        }
    },
    function(err, result) {
        console.log(err);
}

I have

{ [MongoError: Error: Unsupported projection option: date_register] name: 'MongoError' }

as error

I'd like to get my users by date_register DESC

Thanks

like image 927
Ajouve Avatar asked Nov 18 '12 18:11

Ajouve


People also ask

Can we use sort with findOne in MongoDB?

findOne(selector) only returns one result from the collection based on the selector and does not allow you to sort. Adding . fetch().

What is findOne in Mongoose?

Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.

What is the difference between find findOne and findById Apis in Mongoose?

If you want to query by a document's _id, use findById() instead of findOne() . Both functions trigger findOne() , the only difference is how they treat undefined . If you use findOne() , you'll see that findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents.

What is sort in Mongoose?

sort() takes an object as parameter where the values are 1 or -1. Use -1 for descending order and 1 for ascending.


1 Answers

This will vary slightly depending on your version of mongoose, but the method signature for findOne looks something like this:

function findOne (conditions, fields, options, callback)

What you intend as options (the sort), mongoose is handling as fields (which fields to load).

You might try explicitly passing null for fields:

models.user.findOne({}, null, { sort: { date_register: -1 } }, callback);

But if you can, you should probably use the query API, which is clearer, like:

models.user.findOne({}).sort({ date_register: -1 }).exec(callback);
like image 55
numbers1311407 Avatar answered Sep 20 '22 01:09

numbers1311407