0

I have two collections users and items and user.profile.savedItems is an array of items saved like so: {"itemId" : "yHud5CWpdPaEc6bdc", "added" : ISODate("2014-09-12T22:28:11.738Z")}

What I am trying to do is to retrieve the items from the user profile (that part works) and to order them according to the added date.

Right now, this is the code that I have:

return {items: Items.find({_id: {$in: _.pluck(Meteor.user().profile.savedItems, 'item')}})};

I don't know if it's possible using regular mongo syntax..

oliv23
  • 109
  • 2
  • 11

1 Answers1

1

You have two options:

  1. Store the items sorted.
  2. Sort the items client-side after reading.

Read unsorted items sorted without client-side sorting is not possible.

heinob
  • 19,127
  • 5
  • 41
  • 61
  • Thanks for the answer. 1. Right now, I am using addToSet and I searched and found the $position operator but it seems like it wouldn't work with addToSet. Although they are already naturally sorted, I just need it in reverse. 2. How would I do that since the items themselves don't have the "added" parameter? – oliv23 Sep 16 '14 at 16:49
  • Check out [this technique](http://docs.mongodb.org/manual/reference/operator/update/sort/#sort-array-of-documents-by-a-field-in-the-documents) for storing an array in inserted order. – wdberkeley Sep 16 '14 at 18:32
  • Third option: place those items in a separate collection and sort them with Mongo. – Hubert OG Sep 16 '14 at 18:58
  • So I tried inserting in order but it seems like meteor's minimongo is behind mongodb and the $sort won't work without $each. But I thought of something else. Could I create a new clone collection of "items" and for each one add the extra property "added" by mapping the corresponding ids? – oliv23 Oct 01 '14 at 20:52