Metero 通过 id 从两个集合映射中获取数据

Metero get data form two collections mapping by id's

本文关键字:集合 两个 映射 数据 获取 id 通过 Metero      更新时间:2023-09-26

我有两个集合,一个包含用户配置文件,另一个包含用户朋友userFriend包含数组调用朋友,它将包含该粒子用户的朋友。 这两个集合之间的关系user_id。 我刚刚编写了一个函数来获取一个用户的朋友配置文件,它正在工作。 但我想知道是否有其他比从一一检索更好的方法。 请在下面找到方法。

import UserFriends from 'TruthHurts/collections/UserFriends';
import UserProfile from 'TruthHurts/collections/UserProfile';
getUserFriends: function(userId){
    var resutls= [],userProfiles;
    var UserFriendsList = UserFriends.findOne({userId: userId});
    for(var i = 0; i < UserFriendsList.friends.length; i++){
      userProfiles = UserProfile.findOne({userId: UserFriendsList.friends[i].friend_id});
      if(userProfiles){
        resutls.push(userProfiles);
      }
    }
    return resutls;
  } 

与其使用for循环和每个id的单独查询,我会使用 MongoDB 的内置$in运算符:

getUserFriends: function(userId){
    var UserFriendsList = UserFriends.findOne({
        userId: userId
    });
    // To extract friend_id's from friends array and store it in such a way that:
    // UserFriendsList.friends = ["1","2","3",...]
    UserFriendsList.friends.forEach(function(each, index, array) {
        array[index] = each.friend_id;
    });
    var userProfiles = UserProfile.find({
      _id: {
        $in: UserFriendsList.friends // $in matches against every _id in friends array
      }
    }).fetch();
    return userProfiles;
}

此方法应比使用 for 循环和单个findOne查询更好。有关参考,请参阅此SO帖子。