i have following 2 monogoose models:
clanmember: tag:string, name:string; war: members:array; #array of tags
i finding array of current members by:
clanmember.find({ 'tag': { $in: membertags #an array of tags } }).limit(membertags.length) .exec(function(err, members) { }
from want execute war.find()
s , add info each member document, this:
clanmember.find({ 'tag': { $in: membertags } }).limit(membertags.length) .exec(function(err, members) { var memberarray = []; (var member in members) { if (members.hasownproperty(member)) { var currentmember = members[member]; war.find({members: currentmember.tag}).exec(function(err, wars) { currentmember.wars = wars; memberarray.push(currentmember); }); } } #i want render here });
after happens, i'd pass whole new array of member objects (with war objects) view:
res.render('members', { members: memberarray, });
what best way of ensuring war.find() functions found , finished executing before passing array render function?
for have use promises. code should below.
var promise = require('promise'); clanmember.find({ 'tag': { $in: membertags } }).limit(membertags.length) .exec(function(err, members) { var promises = []; var memberarray = []; members.foreach((member)=>{ var currentmember = member; let warpromise = war.find({members: currentmember.tag}).exec().then(function(wars) { currentmember.wars = wars; memberarray.push(currentmember); return true; }).catch(function(err){ throw err; }); promises.push(warpromise); } }); promise.all(promises).then(function(result){ #i want render here }).catch(function(err){ }); });
here promise.all() function ensure previous promises has been completed. , can give response then.
Comments
Post a Comment