javascript - Integrating asynchronous mongo call within an inner forEach loop -
i got 2 loops, outer loops on users , inner 1 loops on venueid's of each user. within inner loop want venue , attach array defined in outer (useritem
). because foreach synchronous , mongo database asynchronous result remains empty. i've tried integrate this answer no avail. how this?
ret = []; users.foreach(function(user) { var useritem = user.getsanitised('adm'); useritem.venues = []; var tmp = []; useritem.adminvenueids.foreach(function(adminvenueid){ tmp.push(function(callback) { venue.findone({_id:adminvenueid}, function(error, venue) { callback(null, venue.toobject()); }); }); }); async.parallel(useritem.venues, function(err, result) { /* code run after calls finished job or when of calls passes error */ if (err) return console.log(err); useritem.venues.push(result); }); ret.push(useritem); });
tried following doesn't work also
users.foreach(function(user) { var useritem = []; async.series({ setuseritem : function(callback) { useritem = user.getsanitised('adm'); callback(null, 'ok'); }, setuservenues : function(callback) { useritem.venues = []; user.adminvenueids.foreach(function(adminvenueid,index) { venue.findone({_id:adminvenueid}, function(error, venue) { useritem.venues.push(venue.toobject()); if((index+1) == user.adminvenueids.length) callback(null, 'ok'); }); }); } }, function(error, results) { if(error) winston.error(error); ret.push(useritem); } ); });
i think might want using mongoose. nodejs application layer on top of mongodb provides more sql experience.
Comments
Post a Comment