问题描述:

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

网友答案:

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.

相关阅读:
Top