0

这是代码,很简单:

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.usernode.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)

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

谢谢提前!

4

2 回答 2

0

您必须考虑没有返回文件的情况。在这种情况下,user1 将为空。并且 .user 的 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');
    }       
});
于 2013-02-05T04:16:15.453 回答
0

也许req.session在那个范围内不存在?

(如果您在上一行访问 user1.user 时没有收到该错误,则表明 v8 正在为其他 .user 访问抛出错误:req.session.user。要么您不在引用req,或请求对象没有附加会话)。

于 2013-02-04T19:31:39.520 回答