1

I have two collections one contain User Profiles and other one contains User Friends userFriend contain array call friends and it will contain that particulater user's friends. the relationship between these two collections are user_id. i just wrote a function to get one users friends profiles and it is working. but i want to know if there any other better way than retrieving it from one by one. please find the method below.

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;
  } 

1 Answers1

0

Instead of using a for loop and separate queries for each id, I would use MongoDB's inbuilt $in operator:

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;
}

This approach should be better than using a for loop and individual findOne queries. For reference see this SO post.

Community
  • 1
  • 1
Soubhik Mondal
  • 2,666
  • 1
  • 13
  • 19