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

share|improve this question
up vote 22 down vote accepted

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);
share|improve this answer
    
it works fine with the api, thanks – Ajouve Nov 18 '12 at 20:26
    
That second example looks broken to me.. Won't .findOne({}).sort(..) return the a record from Mongoose then sort the result? Ie. the sort will only be applied to the single record returned which, assuming Mongoose uses the underlying .findOne() function in Mongo, returns the first document according to the natural order which reflects the order of documents on the disk. docs.mongodb.org/manual/reference/method/db.collection.findO‌​ne – Molomby Oct 19 '15 at 2:25
3  
No, because of the way the way mongoose queries work. Many mongoose methods, if not passed a callback, will return a Query object which allows the query sent to mongoose to be built up in parts. In the example findOne and sort are chained and finally constructed into a query when exec is called. – numbers1311407 Oct 19 '15 at 14:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.