简体   繁体   English

遍历数组并执行MongoDB查询(NodeJS)

[英]Looping through array and executing MongoDB query (NodeJS)

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. 我想遍历该数组,获取每个收藏夹的ID,然后在mongo DB的歌曲集中为该ID做一个.find(),获取歌曲的艺术家,并将其添加到数组中。

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.) 但这似乎不起作用,(主要是因为Mongo / MongoJs是异步的。)

What is the proper way to do something like this? 做这样的事情的正确方法是什么?

You can use $in to query an field that match with any value in the specified array. 您可以使用$in查询与指定数组中的任何值匹配的字段。

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

db.songs.find({ _id: { $in: favoritesId }}, function(err, songs){
  // do you favor 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM