How to return table in JavaScript in Sails.js from multiple models -
i got 2 models, user , friend. in friend got 2 columns( userid1, userid2) want find in friend rows userid1 specified, , table these rows want return table users id = userid2
index: function(req, res, next) { friend.find({userid1 : req.session.user.id}, function foundusers(err, friends) { if (err) return next(err); // pass array down /views/index.ejs page res.view({ friends: friends }); }); }
this code above return table friends(userid1, userid2) userid1 specified, how return table users (from model user) id = userid2 ??
so, sounds you're using friend
model join table represents friendship between 2 users. query have in code gets of records join table userid1
id of logged in user, , each of records, want full user
object user id matches userid2
column. if case, full code like:
index: function(req, res) { friend.find({userid1 : req.session.user.id}) .exec(function foundusers(err, friend_records) { if (err) return res.servererror(err); // array of userid2 values, using sails.util.pluck, // lodash's _.pluck var friend_ids = sails.util.pluck(friend_records, 'id'); // user records users. using array // in criteria makes waterline "in" query user.find({id: friend_ids}).exec(function(err, friends) { // pass array down /views/index.ejs page res.view({ friends: friends }); }); }); }
a couple of notes:
- you should never use
next
in controller code, error handling. if there's error, handle using response. savenext
policies unless really, really intend controller handle response you. - sails v0.10 (currently in beta) includes support associations, handle join tables you.
Comments
Post a Comment