findOne无法在mongoose / node

时间:2016-04-25 08:11:48

标签: node.js mongodb mongoose

这个问题与NodeJS平台的mongoose模块有关。

当我运行以下内容时,如何从数据库获取响应?:

router.get('/profileSettings', securePages, function(req, res, next){
    databaseUserModel.findOne({'profileID':req.session.facebookProfileId}, function(err, userFromDB) {
        if(userFromDB){
            done(null, userFromDB);
        } else {
            console.log('Result does not exist');
       }
    });

    res.render('profileSettings', {title:siteName + ': Profile Settings', user:userFromDB});
})

对于我来说似乎没有用,因为userFromDB似乎不存在 - 无论是在findOne还是res.render方法中! (未定义为准确)

我的databaseUserModel如下所示:

var databaseUser = new mongoose.Schema({
   profileID:String,
   fullname:String,
   profilePic:String,
   email:String,
   birthday:String,
   location:String,
   about:String
});

var databaseUserModel = mongoose.model('databaseUser', databaseUser);

错误消息是:

ReferenceError: userFromDB is not defined
at Object.handle (/Users/shayan/Repos/imo/routes/routes.js:75:84)
at next_layer (/Users/shayan/Repos/imo/node_modules/express/lib/router/route.js:103:13)
at Object.securePages [as handle] (/Users/shayan/Repos/imo/routes/routes.js:20:13)
at next_layer (/Users/shayan/Repos/imo/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/Users/shayan/Repos/imo/node_modules/express/lib/router/route.js:107:5)
at /Users/shayan/Repos/imo/node_modules/express/lib/router/index.js:205:24
at Function.proto.process_params (/Users/shayan/Repos/imo/node_modules/express/lib/router/index.js:269:12)
at next (/Users/shayan/Repos/imo/node_modules/express/lib/router/index.js:199:19)
at next (/Users/shayan/Repos/imo/node_modules/express/lib/router/index.js:176:38)

我觉得这可能是非常简单的我可能会失踪但是我只是在NodeJS上弄脏了(实际上是整体开发)。我之前为我的公司编写了一种小众语言(他们开发了它)所以请耐心等待。

任何输入都会帮助你!我真的被困在这个

PS:我的猫鼬对象可以用来存储数据。

1 个答案:

答案 0 :(得分:1)

You can use result data only inside mongoose query i.e. you cannot use value return from userFromDB outside of findOne. Put your res.render inside it will solve.

router.get('/profileSettings', securePages, function(req, res, next){
    databaseUserModel.findOne({'profileID':req.session.facebookProfileId}, function(err, userFromDB) {
        if(userFromDB){
            res.render('profileSettings', {title:siteName + ': Profile Settings', user:userFromDB});
        } else {
            console.log('Result does not exist');
       }
    });
})