Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort the array inside the meteor collection

Tags:

meteor

I have such collection structure:

{
    _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"
},
...

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

I've 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 nothing of this worked.

Is it even possible to do that now?

like image 855
eawer Avatar asked Jan 11 '23 09:01

eawer


1 Answers

Sort is used only to sort whole documents. You'd need to do a findOne and then sort the images array separately. For example:

var images = Users.findOne({username: "John"}).images;
return _.sortBy(images, function(image){ return image.created; });
like image 138
David Weldon Avatar answered Jan 21 '23 14:01

David Weldon