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

前端 未结 4 740
栀梦
栀梦 2021-01-05 05:10

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: {$nat

相关标签:
4条回答
  • 2021-01-05 05:27

    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.

    0 讨论(0)
  • 2021-01-05 05:30

    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}});
    
    0 讨论(0)
  • 2021-01-05 05:33

    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;
    
    0 讨论(0)
  • 2021-01-05 05:45

    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.

    0 讨论(0)
提交回复
热议问题