Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sorting in Mongoose doesnt work correctly

Sorting in Mongoose doesnt work correctly


Sorting doesnt work with Mongoose, but I don't understand how this can be possible since I've searched so much! Any time I tried it didn't work. Here is my code

Pics.find({}).limit(8).populate('creator').sort("created_at", 1).execFind(function(err, docs){

I get:

TypeError: Invalid sort() argument. Must be a string or object.
at Query.sort (/Users/n/Proj/feetshot/node_modules/mongoose/lib/query.js:755:11)
at /Users/n/Proj/feetshot/app.js:112:45
at callbacks (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:272:11)
at param (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:280:4)
at Object.handle (/Users/n/Proj/feetshot/node_modules/express/lib/router/index.js:45:10)
at (/Users/n/Proj/feetshot/node_modules/express/node_modules/connect/lib/http.js:204:15)
at Context. (/Users/n/Proj/feetshot/node_modules/passport/lib/passport/context/http/actions.js:64:8)
at SessionStrategy.pass (native)

How can I make sort working?

Here is my schema:

var PicSchema = new Schema({
creator: { type: Schema.ObjectId, ref: 'Users' }
, body: String
, created_at: { type: Date, default: }
, link: { type: String, index: { unique: true } }
, twitter_id: { type: String, index: { unique: true } }
, tags: [String]
  , likes: [{ type: Schema.ObjectId, ref: 'Users' }]
Problem courtesy of: nick


Based on your error message you must be using Mongoose 3.x, however you're using the 2.x sort method parameter style. Either switch to the 2.7.0 Mongoose release or change your sort usage to sort('created_at'). From the 3.x source:

* sort
* Sets the sort order. Accepts a single parameter, either an object or string.
* If an object is passed values allowed are 'asc', 'desc', 'ascending', 'descending', 1, -1.
* If a string is passed it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.
* Examples:
* // these are equivalent
* query.sort({ field: 'asc', test: -1 });
* query.sort('field -test');
* @param {Object|String}
* @api public
Solution courtesy of: JohnnyHK


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sorting in Mongoose doesnt work correctly


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription