Reputation: 4482
I am querying a user in a friend request array which works, but the check which I am using userAdd for keeps showing up as undefined. Anyone know why it is showing up as undefined?
This is the 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 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
});
}
}
});
};
Upvotes: 0
Views: 133
Reputation: 54514
It is async, so you need to use the callback way to chain the actions. You can try some node modules like async or step to achieve it in a better syntax.
Btw, I don't think you need to loop through users.forEach(function(user)
.
If you use Step, you 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 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
});
}
);
}
}
});
};
Upvotes: 1