0

I am using mongodb and am building an application with two collections: users and items.
I'd like for users to be able to save items that they like and go to their saved items page where the items would be displayed in the reverse order that they were saved (last saved appears first).

At the moment, I am adding every saved item's id along with the savedDate to the user's profile savedItems array like so:

user profile
{
  savedItems: [{id: "", savedDate: ""}, {id: "", savedDate: ""}, etc...]
}

Whenever I need to retrieve those items, I query the items collection for objects with ids $in this array. Like this:

var items = Items.find({_id: {$in: _.pluck(user.savedItems, 'id')}});

The problem here is that I can't order those items according to the addedDate.

So is it possible to map the addedDate onto every object of the retrieved items?
(Something like: if retrievedItems.id == savedItems.id, then push the addedDate there.)

Which would result in an items array like this:

[
  {id:"", itemName:"", price: "", [...], savedDate: ""},
  {id:"", itemName:"", price: "", [...], savedDate: ""},
  [...]
]

Thank you.

oliv23
  • 109
  • 2
  • 11

1 Answers1

0

JSFIDDLE

I created two function to help you do it:

function mergeDates(listDates, listItems) {

    for (var i = 0; i < listDates.length; i++) {
        var index = findListIndex(listItems, listDates[i].id);
        if (index != null) listItems[index].savedDate = listDates[i].savedDate;
    }

    return listItems;

}

function findListIndex(listItems, id) {
    for (var i = 0; i < listItems.length; i++) {
        if (listItems[i].id == id) return i;
    }
    return null;
}

The first one, mergeDates, takes your first list wich contains the date, the second list, listItems, is the list of your items.

I loop the list with dates, and for each items in it, i call a second function that return the index of the same element in the second list, so findListIndex will search all element and return it's index when he find the same id.

Now the function mergeDates, with the newly found index, will add the value savedDate to your listItems and make it equals to the one on the listDates !

Then the function return the list with all the info of the items, including the dates!

Here is how to call the function:

var listWithDate = mergeDates(savedItems, items);

Hope it helps !

Shryme
  • 1,572
  • 1
  • 14
  • 22
  • Thanks a lot. Though in the end, it is nesting two for loops; how efficient do you think this would be with, say, 10k items? Wouldn't it be better to denormalize the items and just copy everything in the savedItems array? – oliv23 Oct 16 '14 at 18:55
  • Well i admit that's it probably not the fastest way to do it, I found [this question](http://stackoverflow.com/questions/17500312/is-there-some-way-i-can-join-the-contents-of-two-javascript-arrays-much-like-i) that can maybe help you! – Shryme Oct 16 '14 at 20:03