javascript - Node.js, MongDB (Mongoose) - Adding to data retrieved. -
i have following code:
user.find({ featuredmerchant: true }) .lean() .limit(2) .exec(function(err, users) { if (err) { console.log(err); return res.status(400).send({ message: errorhandler.geterrormessage(err) }); } else { _.foreach(users, function(user){ _.foreach(user.userlistings, function(listing){ listing.find({ user: user }).populate('listings', 'displayname merchantname userimagename hasuploadedimage').exec(function(err, listings){ user.listings = listings; }); }); }); res.jsonp(users); } });
as can see trying add retrieved listings each 'user' in 'users' lean object have returned. if console.log(user) inside listing.find exec method after adding 'user.listings = listings', result expect; user object listings property, listing property containing listings retrieved.
however, if console.log 'users' object, listings each user cannot found.
i'm pretty sure i'm doing stupid here, cannot work out what. appreciated. thank you!
you right stupid thing !
no offense, think common mistake :)
_.foreach(users, function(user){ _.foreach(user.userlistings, function(listing){ listing.find({ user: user }) .populate('listings', 'displayname merchantname userimagename hasuploadedimage') .exec(function(err, listings){ user.listings = listings; }); }); }); // listing.find inside foreach hasn't finish yet // suppose it's asynchronous call res.jsonp(users);
maybe can fix using promises. example q library.
var promises = []; _.foreach(users, function(user){ _.foreach(user.userlistings, function(listing){ var deferred = q.defer(); promises.push(deferred); listing.find({ user: user }) .populate('listings', 'displayname merchantname userimagename hasuploadedimage') .exec(function(err, listings){ user.listings = listings; deferred.resolve(user); }); }); }); q .all(promises) .done(function(allusers){ // want here users res.jsonp(allusers); });
check , don't hesitate fix because can't test it.
Comments
Post a Comment