app.get('/showme', function (req, res){
console.log(req.session.user);
UserModel.findOne({ user: req.session.user }, function (err, user){
if (err) throw err;
console.log(user);
res.send('Look');
});
});
When this is executed, I received correctly the user in the terminal, but, after that, suddenly the app crashed, and this is the error TypeError: Cannot read property '_id' of null. The req.session.user is defined, and in the app. This is not the first time UserModel.findOne({ user: req.session.user } called, but is the only one that returns this error! Why this happen?
EDITED:
And this is the user's schema
var userschema = new mongoose.Schema({
user: String,
pass: String,
mail: String,
avatar: String,
});
EDITED:
I don't know why, but I don't why, but I don't get any error with UserModel.find(). It only happens with UserModel.findOne().
EDITED:
app.get('/showme', function (req, res){
UserModel.find({ user: req.session.user }, function (err, user){
for (var i = 0; i <= user[0].following.length; i++) {
UserModel.find({ _id: user[0].following[i] }, function (err, users){
var userss = [];
users[i] = users[i];
console.log(users);
});
}
});
res.send('Hello');
});
And in this code, the first time UserModel doesn't returns any error, but the second does!
This is what i received in the terminal:
[ { __v: 2,
_id: 50e1d852d7b6f9e1be000003,
avatar: './users/rodridev/full_Mgs-solid-snake.jpg',
user: 'rodridev',
notification: [],
followers: [ '50e1cfda6e63107eb6000003' ],
following: [ '50e1cfda6e63107eb6000003' ],
,
,
undefined ]
[ , , , undefined ]
[ { __v: 1,
_id: 50e214171553600000000003,
avatar: './users/kirbo/8816.masterchief.jpg-610x0.jpg',
user: 'kirbo',
followers: [ '50e1cfda6e63107eb6000003' ],
following: [],
imagen: [] },
,
,
undefined ]
And this is the error that appears down this. The same as before: TypeError: Cannot read property '_id' of null
Try
UserModel.findOne({ _id: req.session.user._id }, function (err, user) {
The problem is that you are asking for a user who has a property called user whose value is the current user. What you really want (I assume) is the user item from the database that is the current session user.
Alternatively, even better, is I like to do
UserModel.findById(req.session.user._id, function (err, user) {