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
findOne(selector) only returns one result from the collection based on the selector and does not allow you to sort. Adding . fetch().
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.
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.
sort() takes an object as parameter where the values are 1 or -1. Use -1 for descending order and 1 for ascending.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With