Sasikanth
Sasikanth

Reputation: 3043

meteor sort by length of the array

I have a question and comment section in my page and comments has facebook like vote option

i want to sort the comments based on the length of the array

this is my document

{
    "_id" : "Xxxx",
    "comments" : [ 
        {
            "cmt_text" : "op1",
             "votes" : [ 
                "Sasikanth", 
                "Sasikanth"
            ]
        }, 
        {
            "cmt_text" : "op2",
             "votes" : [ 
                "Sasikanth", 
                "Sasikanth", 
                "Sasikanth"
            ]
        }, 
        {
            "cmt_text" : "op3",
            "votes" : [ 
                "Sasikanth"
            ]
        }
    ],
    "question" : "test question"
}

i want the comments based on the length of the votes.

Upvotes: 1

Views: 725

Answers (1)

Serkan Durusoy
Serkan Durusoy

Reputation: 5472

You have a number of options:

  1. You can use transform to also get the array length as an additional document property. But that won't be reactive.

  2. You can hook into observeChanges to get your count (which is documented with an example on the official docs), but that will be hard to maintain.

  3. You can use a third party package like collection2 to publish virtual fields that are computed from other info (ie length of the array)

  4. You can take the length of the array within your template helper, but you'd need to rewind the data if you go through all comments

  5. Just have a voteCount property and $inc int when you $push votes to the array.

I'd go for 5. In fact, I am currently working on a very similar functionality on a project and that's how I do it.

Upvotes: 2

Related Questions