Erlend V
Erlend V

Reputation: 518

Meteor.js: Find all documents and return in reverse natural order

I am trying to return all documents in a collection, to use it with an {{#each}} in my template. My code looks like this:

return Answers.find({}, {sort: {$natural:-1}})

But the documents are returned in natural order (not reverse). Does anyone know why? I got the $natural selector from the MongoDB documentation, so I don't see what's wrong.

Upvotes: 8

Views: 8927

Answers (4)

Rondo
Rondo

Reputation: 3721

I think you might be confusing definitions of 'natural order' here. One the one hand there is a natural sort order for letters/strings (A,B,C...) and numbers (1,2,3...).

But in the case of mongo, 'natural' refers to the order the data was written to disk. '{$natural:1}' returns 'documents in the order they exist on disk...' and, so '{$natural:-1}' reverses that (http://docs.mongodb.org/manual/reference/operator/meta/natural/).

So without the code that writes the data and some insight into how it was written to disk, we cannot test your hypothesis that it is not working correctly.

Upvotes: 0

Justin McCandless
Justin McCandless

Reputation: 681

As a workaround you could do this:

return Answers.find().fetch().reverse();

I know it would be nicer to do it via the sort parameter, but I don't think it's possible right now.

Upvotes: 1

DNJohnson
DNJohnson

Reputation: 776

Sort isn't a parameter but a separate function to be called after find() on the resulting Cursor object. This is the method that the MongoDB documentation is referring to and works with drivers such as MongoJS:

return Answers.find().sort({$natural: -1});

It seems Meteor hasn't added the sort() function to their implementation of Cursor, so an alternate solution would be to sort by the _id field which is generated based on date (and hence insertion order):

return Answers.find({}, {sort: {'_id': -1}});

Upvotes: 2

sohel khalifa
sohel khalifa

Reputation: 5588

Can't tell why don't it returns in reverse order.

But you can create an array in the template helper method and return reverse of an array using array.sort() or array.reverse() functions.

For ex: Say you Answers collection looks like this:

Answers({ansNo: 1, ansBody: "body1"},
        {ansNo: 2, ansBody: "body2"},
        {ansNo: 3, ansBody: "body3"});

And the array to be returned is:

var AnswersArr = new Array();

then in your template helper :->

var tempCollection = Answers.find({});
tempCollection.forEach(function(data){
    var obj = {ansNo: data.asnNo, ansBody: data.ansBody};
    AnswersArr.push(abj);
});

AnswersArr.sort(function(a, b){return b.ansNo - a.ansNo;});  //sort in reverse order

return AnswersArr;

Upvotes: 3

Related Questions