0

I have an object name profile that contains a favorites array that looks like this...

{favorites: [
    { name: 'Love Song',
      id: 'Itja90E2tIE'},
    { name: 'I Need Your Love',
      id: 'AtKZKl7Bgu0'}
]}

I want to loop through that array, get the id of each favorite, and do a .find() for that ID in my songs collection of my mongo DB, get the song's artist, and add it to the array.

I've tried something like...

for(var i=0; i<profile.favorites.length; i++) {
    db.songs.find({"_id" : profile.favorites[i].id}, {"artistName" : 1}, function (e, result){
            profile.favorites[i]["artistName"] = result[0].artistName;
        });
    }

But that doesn't seem to working, (primarily because Mongo/MongoJs is async.)

What is the proper way to do something like this?

1 Answer 1

1

You can use $in to query an field that match with any value in the specified array.

favoritesId = favorites.map(function(favorite){ return favorite.id; });

db.songs.find({ _id: { $in: favoritesId }}, function(err, songs){
  // do you favor 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.