2

i have a requirement where i need to get the friends of user. I have made two collections named User and Friends. The code that i use to access the data from the Friends and User is:

var friend = Friends.find({acceptor:req.currentUser.id,status:'0'},function(err, friends) {
    console.log('----------------friends-----------------'+friends.length);

  });

console.log is giving me the desired results for friends.Now if i use friend to access the User data like the one given i am not getting the result that i need.

var user = User.find({_id:friend.requestor},function(err, users) { 
     console.log('----------------user-----------------'+users.length);
});

how can i join the two queries to get the desired result.Please help

Dar Hamid
  • 1,949
  • 4
  • 21
  • 27
  • 1
    i think this is more a problem of you DB design than of how to query this ... add the friends as an array of IDs to the User Schema. then query the user (and get the array) and after that get all friend-User (http://stackoverflow.com/questions/5818303/how-do-i-perform-this-query-in-mongoose-mongodb-for-node-js). – Philipp Kyeck Dec 07 '11 at 07:41
  • pkyeck is right, you should add the array of friends to the user since that way you would only need to perform one query => optimization – alessioalex Dec 07 '11 at 08:48
  • yes that way it worked.had a problem in rendering the file, if i used loop.Use of array eliminated that.Thanks – Dar Hamid Dec 09 '11 at 07:25

1 Answers1

3

I'd suggest you try to denormalize the data instead of going down the SQL path:

User {
  "FirstName" : "Jack",
  "LastName" : "Doe",
  // ...
  // no friend info here
}

Put denormalized information in the list of friends. Don't use an embedded array, because you probably don't need to fetch all friend ids every time you fetch a user. The details of the data structure depend on the relations you want to support (directed vs. undirected, etc.), but it would roughly look like this:

FriendList {
  OwnerUserId : ObjectId("..."),
  FriendUserId : ObjectId("..."),
  FriendName: "Jack Doe"
  // add more denormalized information
}

Now, to display the list of friends of a user:

var friends = db.FriendList.find({"OwnerUserId" : currentUserId});

The downside is that, if a friend changes her name, you'll have to update all references of that name. On the other hand, that logic is trivial and that the (typically much more common) query "fetch all friends" is super fast, easy to code, and easy to page.

mnemosyn
  • 45,391
  • 6
  • 76
  • 82