我正在查询有效的朋友请求数组中的用户,但我使用userAdd的检查会一直显示为未定义。任何人都知道为什么它会显示为未定义?
这是代码:
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 a diff page saying that is not a 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
});
}
}
});
};
答案 0 :(得分:1)
它是异步的,因此您需要使用回调方式来链接操作。您可以尝试使用async或step等节点模块,以更好的语法实现它。
顺便说一句,我认为你不需要遍历users.forEach(function(user)
。
如果您使用Step,则可以执行
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 a diff page saying that is not a 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
});
}
);
}
}
});
};