node.js - Sailsjs: How to populate association after *update* to model? -
i have following controller code works index, show, create methods update fails when include populate - doing wrong?
// user list index: function(req, res) { user.find() .populate('profile') .exec(function(err, users) { if (err) return res.json(err, 400); if (!users) return res.json(users, 404); res.json(users, 200); }); }, // single user show: function(req, res) { user.findone({ username: req.param('username') }) .populate('profile') .exec(function(err, user) { if (err) return res.json(err, 400); if (!user) return res.json(user, 404); res.json(user, 200); }); }, // create user create: function(req, res) { user.create(req.body, function(err, user) { if (err) return res.json(err, 400); person.create({user: user.id, slug: user.username}, function(err, profile) { if (err) return res.json(err, 400); user.update(user.id, {profile: profile.id}) .populate('profile') .exec(function(err, user) { if (err) return res.json(err, 400); }); user.profile = profile; res.json(user, 200); }); }); }, // update user update: function(req, res) { var username = req.param('username'); user.update({ username: username }, req.body) .populate('profile') .exec(function(err, user) { if (err) return res.json(err, 400); res.json(user, 201); }); },
as per documentation update
function takes callback passes updated records. example doc :
// example, update user's name, // .update(query, params change, callback) user.update({ name: 'sally' },{ phone: '555-555-5555' }, function(err, users) { // error handling if (err) { return console.log(err); // updated users successfully! } else { console.log("users updated:", users); } });
applied code, :
// update user update: function(req, res) { var username = req.param('username'); user.update({ username: username }, req.body) .exec(function(err, users) { if (err) { return res.json(err, 400); } var user = users.slice(0,1); // take first user in array user.findone(user.id) // may try user._model(user) instead avoid roundtrip db. .populate('profile') .exec(function(err, user) { if (err) { return res.json(err, 400); } res.json(user, 201); }); }); }
Comments
Post a Comment