无法从Mongoose读取'null'返回的对象

时间:2013-02-04 19:28:34

标签: node.js mongodb express mongoose

这是代码,非常简单:

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!');

      }

});

console.log正确返回user1.user,但是当node.js进入if语句时,我收到此错误:

/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)

为什么会发生这种情况,我该如何解决这个问题?

谢谢你的进步!

2 个答案:

答案 0 :(得分:0)

该范围内可能不存在req.session

(如果你没有在上一行访问user1.user时遇到错误,那么v8就会抛出另一个.user访问错误:req.session.user。要么你不在一个引用req的闭包,或者请求对象没有附加会话。

答案 1 :(得分:0)

您必须考虑未返回任何文档的情况。在这种情况下,user1将为null。并且.user of null未定义。所以你可以修改下面的代码来解释所有情况:

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');
    }       
});