Sort an array inside a meteor collection

I have a collection structure like this:

{
    _id: "JPsqqGJBgpwix5AqM",
    images: [
        {
            id: 123456,
            created: Thu Nov 14 2013 22:58:11 GMT+0200 (EET),
            height: 115,
            width: 350,
            url: "http://www.test.com/alckxm.jpg"
        },
        {
            id: 123456,
            created: Thu Jan 24 2013 01:46:55 GMT+0200 (EET),
            height: 115,
            width: 350,
            url: "http://www.test.com/awerrkxm.jpg"
        }
    ],
    username: "John"
},
...

I need to return all images from this collection, sorted by date.

I tried all of the following:

return Users.findOne({username: "John"}, {created: 1})
return Users.findOne({username: "John"}, {"images.created": 1})
return Users.findOne({username: "John"}, {sort: {created: 1}})
return Users.findOne({username: "John"}, {sort: {"images.created": 1}})

but none of this worked out.

Is it possible to do it now?

+4
source share
1 answer

Sorting is used only for sorting entire documents. You will need to do findOneand then sort the array of images separately. For example:

var images = Users.findOne({username: "John"}).images;
return _.sortBy(images, function(image){ return image.created; });
+9
source

All Articles