javascript - Why variable shows up as undefined? -
i querying user in friend request array works, check using useradd keeps showing undefined. know why showing undefined?
this code:
exports.searchpost = function(req, res, err) { user.find({$or:[ {firstname: req.body.firstname}, {lastname: req.body.lastname}, {email: req.body.email}, {phone: req.body.phone}] }, function(err, users) { if(err) { return res.render('searcherror', {title: 'weblio'}); } else { if(req.body.firstname=== '' && req.body.lastname==='' && req.body.email==='' && req.body.phone=== '') { //maybe diff page saying not valid search page return res.render('searcherror', {title: 'weblio'}); } else { var useradd; console.log('addman'); users.foreach(function(user) { user.findbyid(req.signedcookies.userid, {friendrequest: user._id}, function() { if(user._id === true ) { console.log('addman1'); return useradd = true; } else { console.log('addman2'); return useradd = false; console.log(user._id); } }) }); console.log(useradd); return res.render('searchresults', {title: 'weblio', usersfound: users, useradded: useradd }); } } }); };
it async, need use callback way chain actions. can try node modules async or step achieve in better syntax.
btw, don't think need loop through users.foreach(function(user)
.
if use step, can do
exports.searchpost = function(req, res, err) { user.find({$or:[ {firstname: req.body.firstname}, {lastname: req.body.lastname}, {email: req.body.email}, {phone: req.body.phone}] }, function(err, users) { if(err) { return res.render('searcherror', {title: 'weblio'}); } else { if(req.body.firstname=== '' && req.body.lastname==='' && req.body.email==='' && req.body.phone=== '') { //maybe diff page saying not valid search page return res.render('searcherror', {title: 'weblio'}); } else { var useradd; console.log('addman'); step( function(){ user.findbyid(req.signedcookies.userid, {friendrequest: user._id}, this); }, function(err, user){ if(user !== null && user._id === true ) { console.log('addman1'); useradd = true; } else { console.log('addman2'); useradd = false; console.log(user._id); } return res.render('searchresults', {title: 'weblio', usersfound: users, useradded: useradd }); } ); } } }); };
Comments
Post a Comment