Mongoose: mongodb sort not working in nodejs

Created on 2 Oct 2016  路  2Comments  路  Source: Automattic/mongoose

SORT function not working properly in the nodejs with mongoose buts works perfectly in mongo shell .

Mongo DB + NodeJS Project:
dependencies
"body-parser": "^1.15.2",
"express": "^4.14.0",
"mongoose": "^4.6.2"

Error: sort() only takes 1 Argument

mongoose.connect('mongodb://localhost:27017/testDB');
var Schema = mongoose.Schema;
var noSchema = new Schema({}, { strict: false });
var data = mongoose.model('tables', noSchema);

data.find().sort({"id": 1}, function(err,docs){
res.json(docs);
})

Most helpful comment

Try moving your callback to .exec:

data.find().sort({"id": 1}).exec(function(err,docs){
  if (err) throw err;
  res.json(docs);
})

Many of the query operators don't accept a final callback and require using exec.

All 2 comments

Try moving your callback to .exec:

data.find().sort({"id": 1}).exec(function(err,docs){
  if (err) throw err;
  res.json(docs);
})

Many of the query operators don't accept a final callback and require using exec.

I'm having a similar issue with the 'sort' option using MongoDB with Express.
I can sort in the Mongo shell but when I use the sort in an Express function
it affects the JSON results by adding something that is non parsible. I guess
the reality is that its probably easier to apply sorting somewhere else. Perhaps
against the JSON object. MongoDB disappoints again.

I used the approach above but got the same parsing error. I just can't understand
why the sort would alter the structure of the JSON result other than to reorder the
entries.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nparsons08 picture nparsons08  路  40Comments

floatingLomas picture floatingLomas  路  61Comments

ChrisZieba picture ChrisZieba  路  76Comments

bendytree picture bendytree  路  53Comments

saudelog picture saudelog  路  79Comments