【问题标题】:Metero get data form two collections mapping by id'sMeteor 通过 id 从两个集合映射中获取数据
【发布时间】:2023-03-16 21:05:01
【问题描述】:

我有两个集合,一个包含用户配置文件,另一个包含用户朋友 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;
  } 

【问题讨论】:

    标签: javascript mongodb meteor reactjs


    【解决方案1】:

    我不会使用 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 post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2023-03-02
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多