Sort All the Things With Mongo and node.js
Sorting shouldn’t be difficult, but through my experience learning meteor I discovered that if mongo likes sort commands one way:
db.posts.find().sort({submitted: -1})
meteor would like them a different way:
Posts.find({}, {sort: {submitted : -1}}
I am adapting one of my meteor projects to use mongo and node.js, connected through mongoose, and fitting in the callback required for node sent me to the google. After a few stackoverflow searches I turned up a several options:
1 2 3 |
|
This option returned a object containing only the entry ids, not the full documents:
1 2 3 4 5 |
|
Another option suggested that converting the result to an Array would complete the query:
1 2 3 |
|
This option resulted in TypeError: Object #<Query> has no method 'toArray'
.
Rather than continuing to search for a snippet to steal, I turned to the source, and it turns out that querying mongo from mongoose is simpler than either of these strategies.
1 2 3 4 5 |
|
Success! Why? Because while mongo itself returns a cursor object which can be transformed into documents using toArray()
, or fetch()
in the case of meteor, mongoose returns a Query object, which will return the full documents once it is passed a callback.
A Query object can be built using method chaining — each method (find | where | limit | select | sort) returns a new Query object, which allows you to build in stages:
1 2 3 4 5 6 7 8 |
|
Another fun bit of javascript/mongoose magic, is that you can indicate sorting in descending order by prefacing the sort string with a “–” :
1 2 3 4 |
|
Awesome.