[javascript] How to sort in mongoose?

I find no doc for the sort modifier. The only insight is in the unit tests: spec.lib.query.js#L12

writer.limit(5).sort(['test', 1]).group('name')

But it doesn't work for me:

Post.find().sort(['updatedAt', 1]);

This question is related to javascript node.js mongodb mongoose

The answer is


This is what i did, it works fine.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

Chaining with the query builder interface in Mongoose 4.

// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
    find({ occupation: /host/ }).
    where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
    where('age').gt(17).lt(66).
    where('likes').in(['vaporizing', 'talking']).
    limit(10).
    sort('-occupation'). // sort by occupation in decreasing order
    select('name occupation'); // selecting the `name` and `occupation` fields


// Excute the query at a later time.
query.exec(function (err, person) {
    if (err) return handleError(err);
    console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})

See the docs for more about queries.


As of October 2020, to fix your issue you should add .exec() to the call. don't forget that if you want to use this data outside of the call you should run something like this inside of an async function.

let post = await callQuery();

async function callQuery() {
      return Post.find().sort(['updatedAt', 1].exec();
}

Post.find().sort('updatedAt').exec((err, post) => {...});

Reference in here: https://mongoosejs.com/docs/queries.html


Starting from 4.x the sort methods have been changed. If you are using >4.x. Try using any of the following.

Post.find({}).sort('-date').exec(function(err, docs) { ... });
Post.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Post.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Post.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });

Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});

In Mongoose, a sort can be done in any of the following ways:

    Post.find({}).sort('test').exec(function(err, docs) { ... });
    Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
    Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
    Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });

This is how I managed to sort and populate:

Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
    // code here
})

app.get('/getting',function(req,res){
    Blog.find({}).limit(4).skip(2).sort({age:-1}).then((resu)=>{
        res.send(resu);
        console.log(resu)
        // console.log(result)
    })
})

Output

[ { _id: 5c2eec3b8d6e5c20ed2f040e, name: 'e', age: 5, __v: 0 },
  { _id: 5c2eec0c8d6e5c20ed2f040d, name: 'd', age: 4, __v: 0 },
  { _id: 5c2eec048d6e5c20ed2f040c, name: 'c', age: 3, __v: 0 },
  { _id: 5c2eebf48d6e5c20ed2f040b, name: 'b', age: 2, __v: 0 } ]

This is how I got sort to work in mongoose.js 2.0.4

var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
  //...
});

UPDATE:

Post.find().sort({'updatedAt': -1}).all((posts) => {
  // do something with the array of posts
});

Try:

Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
  // do something with the array of posts
});

Mongoose v5.x.x

sort by ascending order

Post.find({}).sort('field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'asc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'ascending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 1 }).exec(function(err, docs) { ... });

Post.find({}, null, {sort: { field : 'asc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'ascending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 1 }}), function(err, docs) { ... });

sort by descending order

Post.find({}).sort('-field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'desc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'descending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: -1 }).exec(function(err, docs) { ... });


Post.find({}, null, {sort: { field : 'desc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'descending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : -1 }}), function(err, docs) { ... });

For Details: https://mongoosejs.com/docs/api.html#query_Query-sort


Others worked for me, but this did:

  Tag.find().sort('name', 1).run(onComplete);

This is how I got sort to work in mongoose 2.3.0 :)

// Find First 10 News Items
News.find({
    deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
    skip:0, // Starting Row
    limit:10, // Ending Row
    sort:{
        date_added: -1 //Sort by Date Added DESC
    }
},
function(err,allNews){
    socket.emit('news-load', allNews); // Do something with the array of 10 objects
})

Update

There is a better write up if this is confusing people; check out finding documents and how queries work in the mongoose manual. If you want to use the fluent api you can get a query object by not providing a callback to the find() method, otherwise you can specify the parameters as I outline below.

Original

Given a model object, per the docs on Model, this is how it can work for 2.4.1:

Post.find({search-spec}, [return field array], {options}, callback)

The search spec expects an object, but you can pass null or an empty object.

The second param is the field list as an array of strings, so you would supply ['field','field2'] or null.

The third param is the options as an object, which includes the ability to sort the result set. You would use { sort: { field: direction } } where field is the string fieldname test (in your case) and direction is a number where 1 is ascending and -1 is desceding.

The final param (callback) is the callback function which receives the collection of docs returned by the query.

The Model.find() implementation (at this version) does a sliding allocation of properties to handle optional params (which is what confused me!):

Model.find = function find (conditions, fields, options, callback) {
  if ('function' == typeof conditions) {
    callback = conditions;
    conditions = {};
    fields = null;
    options = null;
  } else if ('function' == typeof fields) {
    callback = fields;
    fields = null;
    options = null;
  } else if ('function' == typeof options) {
    callback = options;
    options = null;
  }

  var query = new Query(conditions, options).select(fields).bind(this, 'find');

  if ('undefined' === typeof callback)
    return query;

  this._applyNamedScope(query);
  return query.find(callback);
};

HTH


with the current version of mongoose (1.6.0) if you only want to sort by one column, you have to drop the array and pass the object directly to the sort() function:

Content.find().sort('created', 'descending').execFind( ... );

took me some time, to get this right :(


As of Mongoose 3.8.x:

model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });

Where:

criteria can be asc, desc, ascending, descending, 1, or -1

Note: Use quotation marks or double quote

use "asc", "desc", "ascending", "descending", 1, or -1


Post.find().sort({updatedAt: 1});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to mongoose

Querying date field in MongoDB with Mongoose Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Mongodb: failed to connect to server on first connect Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongoError: Topology was destroyed Difference between MongoDB and Mongoose How can you remove all documents from a collection with Mongoose? E11000 duplicate key error index in mongodb mongoose