This is the code, is very simple:
usermodel.findOne({ user: req.params.id }, function (err, user1){
if (err) throw err;
console.log(user1.user);
if (req.session.user != user1.user) {
console.log('Different user!');
}
});
The console.log returns properly the user1.user, but, when node.js gets in the if statement, I receive this error:
/root/pix/node_modules/mongoose/lib/utils.js:434
throw err;
^
TypeError: Cannot read property 'user' of null
at Promise.<anonymous> (/root/pix/app.js:168:38)
at Promise.addBack (/root/pix/node_modules/mongoose/lib/promise.js:128:8)
at Promise.EventEmitter.emit (events.js:96:17)
at Promise.emit (/root/pix/node_modules/mongoose/lib/promise.js:66:38)
at Promise.complete (/root/pix/node_modules/mongoose/lib/promise.js:77:20)
at Query.findOne (/root/pix/node_modules/mongoose/lib/query.js:1600:30)
at exports.tick (/root/pix/node_modules/mongoose/lib/utils.js:429:16)
at Collection.findOne
(/root/pix/node_modules/mongodb/lib/mongodb/collection.js:975:5)
at Cursor.toArray (/root/pix/node_modules/mongodb/lib/mongodb/cursor.js:159:9)
at Cursor.each (/root/pix/node_modules/mongodb/lib/mongodb/cursor.js:199:11)
Why this happens, and how can I resolve this?
Thank's advance!
Perhaps req.session doesn't exist in that scope?
(If you don't get that error accessing user1.user on the previous line, then it follows that v8 is throwing the error for the other .user access: req.session.user. Either you aren't inside of a closure that has a reference to req, or the request object has no session attached).
You have to account for cases where no document is returned. In such cases user1 will be null. And .user of null is undefined. So you could just modify the code as below to account for all cases:
usermodel.findOne({ user: req.params.id }, function (err, user1) {
if (err) throw err;
console.log(user1.user); // will be null if user does not exist
if(user1 != null) {
if(req.session.user != user1.user) {
console.log('Different user!');
}
else
console.log('Same user');
}
else {
console.log('User does not exist');
}
});