1

I have a collection defined with the following structure:

// Websites
{
    _id: "adasdasda",
    title: "Site 1",
    comments: [{
        text: "nice site 2014",
        createdOn: "Sat Dec 26 2014 11:28:57 GMT+0100 (CET)"
    }, {
        text: "nice site 2015",
        createdOn: "Sat Dec 26 2015 11:28:57 GMT+0100 (CET)"
    }]
}

I want to display this information with a proper order of comments. That means in my case the newest comments first.

I tried using:

Websites.findOne({_id:this.params._id}, {sort:{"comments.createdOn": 1}});

and:

Websites.findOne({_id:this.params._id}, {sort:{"comments.createdOn": -1}});

but the order remains unchanged - the oldest comments first.

Any idea what I'm missing?

MasterAM
  • 16,283
  • 6
  • 45
  • 66
sziolkow
  • 173
  • 1
  • 12

1 Answers1

1

sort works at the document level.

This will fetch all of the matching documents, sort them based on the first entry in the sub-document (the creation time of the first element in the array of each document) and return the first document in the list.

Since you already query by _id, this sorting is pretty much futile.

Meteor does not really support sub-document reactivity, so you can either:

  1. flatten the design, separating the comments into a their own collection (this is probably what I would do with Meteor in your case).
  2. transform the documents into a data structure that sorts them as desired (which could be a headache when dealing with reactivity).
  3. insert them at the order that you want in the first place.
  4. take care of sorting during the publication by manually manipulating the cursor or by using the Mongo aggregation framework.

If the nesting is not a requirement, I would suggest flattening the design.

Here are some pointers to related SO and Meteor forum questions:

Community
  • 1
  • 1
MasterAM
  • 16,283
  • 6
  • 45
  • 66