"无法读取null的属性`message`"用猫鼬连接到mongodb

时间:2014-04-13 15:46:36

标签: node.js mongodb express mongoose

我正在为我的MEAN应用创建一个步行骨架。我成功连接到mongodb(multivision db打开),但继续前进我在尝试将消息打印到浏览器窗口时收到标题中描述的错误:

error message

mongoose.connect('mongodb://localhost/multivision');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error...'));
db.once('open', function callback() {
    console.log('multivision db opened');
});

var messageSchema = mongoose.Schema({message: String});
var Message = mongoose.model('Message', messageSchema);
var mongoMessage= new Message({message: 'Hello mongoDB here'});
console.log(mongoMessage.message);
Message.findOne().exec(function(err, messageDoc) {
    mongoMessage = messageDoc.message;
})

app.get('*', function(req, res) {
    res.render('index', {
        mongoMessage: mongoMessage
    });
});

1 个答案:

答案 0 :(得分:4)

您需要保存mongoMessage才能查询它:

mongoMessage.save(function(err, doc) {
    Message.findOne().exec(function(err, messageDoc) {
        mongoMessage = messageDoc.message;
    });
});