Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a Meteor collection by time of insertion?

I am working on my first project using Meteor, and am having some difficulty with sorting.

I have a form where users enter aphorisms that are then displayed in a list. Currently the most recent aphorisms automatically display at the bottom of the list. Is there an easy way to have the most recent appear at the top of the list instead?

I tried:

   Template.list.aphorisms = function () {     return Aphorisms.find({}, {sort: {$natural:1}}); }; 

And am stumped because the Meteor docs don't have many examples.

like image 905
squeezemylime Avatar asked Dec 19 '12 17:12

squeezemylime


People also ask

How do I sort a collection in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

What is $natural in MongoDB?

The ({$natural − 1}) works like LIFO(LAST IN FIRST OUT), that means last inserted document will be shown first. Let us create a collection with documents − > db.

What is Meteor collection?

Collections are Meteor's way of storing persistent data. The special thing about collections in Meteor is that they can be accessed from both the server and the client, making it easy to write view logic without having to write a lot of server code.


2 Answers

Assuming that the date_created is in a valid date format along with the timestamp, You should insert the parsed value of date_created using Date.parse() javascript function, which gives the number of milliseconds between January 1, 1970 and date value contained in date_created.

As a result of that, the most recently added record will contain greater value of date_created than the record inserted before it.

Now when fetching the records, sort the cursor in descending order of the date_created parameter as:

 Aphorisms.find({}, {sort: {date_created: -1}}); 

This will sort records from newer to older.

Hope this helps.

like image 183
sohel khalifa Avatar answered Nov 16 '22 00:11

sohel khalifa


I've found the following to be a cleaner solution:

   Template.list.aphorisms = function () {       return Aphorisms.find().fetch().reverse();    }; 

Given that entire collection already exists in the reverse order that you would like, you can simply create an array of all the objects and reverse the order.

like image 32
Samuel Ellis Avatar answered Nov 16 '22 01:11

Samuel Ellis