How to sort a collection by date in MongoDB?

后端 未结 10 2029
失恋的感觉
失恋的感觉 2020-12-07 14:27

I am using MongoDB with Node.JS. I have a collection which contains a date and other rows. The date is a JavaScript Date object.

How can I sort this col

10条回答
  •  Happy的楠姐
    2020-12-07 14:44

    With mongoose I was not able to use 'toArray', and was getting the error: TypeError: Collection.find(...).sort(...).toArray is not a function. The toArray function exists on the Cursor class from the Native MongoDB NodeJS driver (reference).

    Also sort accepts only one parameter, so you can't pass your function inside it.

    This worked for me (as answered by Emil):

    collection.find().sort('-date').exec(function(error, result) {
      // Your code
    })
    

提交回复
热议问题