Reputation: 1725
I got 2 models, User and Friend. In friend i got 2 columns( UserId1, UserId2) I want to find in Friend rows where UserId1 is specified, and then from the table with these rows i want to return table with Users with Id = UserId2
index: function(req, res, next) {
Friend.find({UserId1 : req.session.User.id}, function foundUsers(err, friends) {
if (err) return next(err);
// pass the array down to the /views/index.ejs page
res.view({
friends: friends
});
});
}
This code above return table with Friends(UserId1, UserId2) where UserId1 is specified, but how to return table with Users (from model User) where Id = UserId2 ??
Upvotes: 0
Views: 1256
Reputation: 24948
So, it sounds like you're using the Friend
model as a join table that represents a friendship between two users. The query you currently have in your code gets all of the records from the join table where UserId1
is the id of your logged in user, and for each of those records, you want to get a full User
object for the user whose id matches the UserId2
column. If this is the case, the full code could be something like:
index: function(req, res) {
Friend.find({UserId1 : req.session.User.id})
.exec(function foundUsers(err, friend_records) {
if (err) return res.serverError(err);
// Get an array of all the UserId2 values, using sails.util.pluck,
// which is essentially Lodash's _.pluck
var friend_ids = sails.util.pluck(friend_records, 'id');
// Get the User records for those users. Using an array
// in the criteria makes Waterline do an "in" query
User.find({id: friend_ids}).exec(function(err, friends) {
// pass the array down to the /views/index.ejs page
res.view({
friends: friends
});
});
});
}
A couple of notes:
next
in your controller code, especially for error handling. If there's an error, handle it using a response. Save next
for policies unless you really, really intend for another controller to handle the response for you.Upvotes: 2