Iván Sánchez Iván Sánchez - 2 months ago 6
Javascript Question

Nodejs variable prints on console but not on the view

the code is this

module.exports = {
index: function (req, res, next) {
//get an array of all users in user collection
Notification.find(function foundNotification(err, notifications) {
if (err) return next(err);
var elusuario=[];
User.findOne(2, function foundUser (err, user) {
if (err) return next(err);
if (!user) return next();
console.log(user);
console.log("----------------------------");
elusuario = user;
console.log(elusuario);
});
res.view({
notifications: notifications,
elusuario: elusuario
});
})

}


};

That is the controller and in the console prints elusuario good but in the view the user hasn't values. why?
i think is something is something related to the globals variables. but i dont know
thanks

EDIT

all right so the method is async. what im trying to do is find the notifications and the user by her user.id and get the user.name so what if i do this

module.exports = {
index: function (req, res, next) {

//get an array of all users in user collection
Notification.find(function foundNotification(err, notifications) {
if (err) return next(err);

User.find(function foundUser (err, users) {
if (err) return next(err);
var usuarios_locotes = [];
_.each(notifications, function (notification) {

_.each(users, function (user) {
if(notification.token_user==user.token){
console.log(user.token);
usuarios_locotes.push(user);
console.log(usuarios_locotes);
};
});
});

res.view({
notifications: notifications,
users: usuarios_locotes
});
});

})
}


};

it still not working? the __.each is an async funtion to?

sorry for all this maybe stupid questions

Answer

The method findOne of User object runs asynchronously. Because of this, you are rendering the view before the findOne returns the user object.

If you put a console.log before the render.view, it'll print the output before the console.log inner findOne method.