Meteor.js: find all documents and return in reverse order

I am trying to return all documents in a collection to use it with {{#each}} in my template. My code is as follows:

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

But documents are returned in kind (and not vice versa). Does anyone know why? I got a natural selector from the MongoDB documentation, so I don't see what is wrong.

+8
mongodb-query meteor
source share
4 answers

I can’t understand why he is not returning in the reverse order.

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

For example: let's say that the Answers collection looks like this:

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

And the returned array:

 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; 
+3
source share

Sorting is not a parameter, but a separate function that will be called after find () in the resulting Cursor object. This is the method referenced by the MongoDB documentation and works with drivers such as MongoJS:

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

It seems that Meteor has not added the sort () function to their Cursor implementation, so an alternative solution would be sorting by _id , which is created based on the date (and therefore the insertion order):

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

As a workaround, you can do this:

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

I know that it would be better to do this through the sort option, but I don't think it is possible right now.

+1
source share

I think you could be misleading the definitions of "natural order" here. On 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 in which data was written to disk. '{$ natural: 1}' returns 'documents in the order in which they exist on disk ...', and therefore '{$ natural: -1}' cancels this ( http://docs.mongodb.org/ manual / reference / operator / meta / natural / ).

Thus, without a code that writes data and some information about how it was written to disk, we cannot test your hypothesis that it does not work correctly.

0
source share

All Articles