How to implement sorting


#1

On what do I sort when there’s no incremental number? Do I need to add that? What about sorting on a date and time stamp like createdAt?


#2

Like a MySQL autoincrement? There is no direct equivalent in MongoDB, so yes, you would have to set that up yourself.

Again, you will need to add that into each of your documents. JavaScript Date objects can be a littel tricky if you’re not familiar them. Generally speaking, it’s safe to use:

createdAt: Date.now()

in your document object and that will be natively sortable (it’s an integer number of ms since midnight Jan 1, 1970). You should also ensure this is added as an index to your collection to improve performance.

Avoid such things as:

createdAt: new Date()

which tries to add a Date object to the collection.

Also, take a look at matb33:collection-hooks to make it easy to manage the automatic addition of fields to documents. @manuel has done a great introduction to this package. I highly recommend it.