Metero 通过 id 从两个集合映射中获取数据
Metero get data form two collections mapping by id's
我有两个集合,一个包含用户配置文件,另一个包含用户朋友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帖子。
相关文章:
- 两个集合mongodb之间的关系
- 如何将两个集合转换为一个集合
- Meteor:如何使用空格键创建包含两个集合数据的树列表
- 如何计算mongodb中两个集合中一个字段的不同值的数量
- 如何使用javascript将两个dom元素集合合并到第三个集合中
- 如何将中的两个geoJSON功能集合添加到两个层组中
- 骨干.js两个层次的集合
- 如何在Meteor中使用两个按时间排序的不同模板显示两个不同的集合
- Metero 通过 id 从两个集合映射中获取数据
- 高效连接两个集合
- 尝试关联两个获得输入值的集合
- 主干集合 - 在集合级别合并两个集合
- 流星:如何在MongoDB中单击一下即可从两个集合中删除两个文档
- 如何在单个反应表中使用两个集合
- 流星:通过 DDP 连接两个应用程序时,模板帮助程序中没有来自远程集合的文档
- 在两个集合之间传递数据 - Meteor JS
- 合并两个集合在 mongodb 中没有地图减少....
- 在主干.js中的两个视图上访问集合
- 从mongodb中的两个集合中的find生成一个json
- 在同一集合中添加两个项目