3
\$\begingroup\$

This is a very simplified version of my query. Is it acceptable to join the two collections for the client with the use of for loops?

There could be up to 2,000 books, which also means there could be an equal number of favorite books per user in the favoriteBooksCollection.

return favoriteBooksCollection
.find({user: current_userId})
.then(function(favorites){

    var bookIds = favorites.map(function (a) {
        return a.bookId
    };

    return BooksCollection
    .find({_id : {$in: bookIds}})
    .sort({timestamp: -1})
    .then(function(books){

     for(var i = 0; i < books.length; i++){
        for(var j = 0; j < favorites.length; j++){
          if(favorites[j].bookId  == books[i]._id){

           //'join' user's myRating to book document here
            books[i].userRating = favorites[j].myRating;  

           };
        };    
    };

      // return books array of objects with newly added UserRating property
      return books;

    });

});
\$\endgroup\$
4
  • 1
    \$\begingroup\$ There is no need to simplify your code to post here, in fact your real, production code would be preferable to get the best out of Code Review. \$\endgroup\$
    – Phrancis
    Commented Aug 18, 2016 at 23:29
  • \$\begingroup\$ This covers the gist of it. I often wonder the best format, since many times I get many upvotes & views, but few if any responses. I sometimes am afraid of the 'TLDR' effect. \$\endgroup\$
    – NoobSter
    Commented Aug 18, 2016 at 23:32
  • 1
    \$\begingroup\$ That TLDR effect may happen more often on Stack Overflow than here. It may be worth your while to read up How do I ask a good question? \$\endgroup\$
    – Phrancis
    Commented Aug 19, 2016 at 3:48
  • \$\begingroup\$ What is your MongoDB server version? \$\endgroup\$
    – Sede
    Commented Sep 16, 2016 at 12:55

1 Answer 1

3
\$\begingroup\$

The nested loops perform books.length * favorites.length iterations (up to 4 million).

Instead build a dictionary of id -> rating, so total iterations max is a sum of lengths.

var favRatings = {}, i, len;

for (i = 0, len = favorites.length; i < len; i++) {
    var fav = favorites[i];
    favRatings[fav.bookId] = fav.myRating;
}

for (i = 0, len = books.length; i < len; i++) {
    var book = books[i];
    var rating = favRatings[book._id];
    if (rating !== undefined) {
        book.userRating = rating;  
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.