我是节点js和mongoose的新手。我在节点js中有以下代码。我想将mongoose的返回userData
记录分配给回调之外的变量user
。
var user = null;
User.findOne({$and: [{"_id": advisorId}, {"role": "advisor"}]}, {firstName:1,lastName:1, '_id':0},
function(err,userData) {
user = userData;
});
我在user
变量中得到返回结果后,我可以直接将其传递给jade视图,如下所示:
TrackSession.find({'advisor_id' : advisorId},fields,function(err, chatHistoryData) {
var jade = require('jade');
var html = jade.renderFile(appRoot+'/views/generatePDFHTML.jade', {'chatHistoryData': chatHistoryData,
'selectedOptions':selectedOptions,
'advisor':user,
'tableHeaders':tableHeaders
});
console.log(html); return false;
});
但是当我尝试这样做时,我得到null
作为user
变量的值。有没有具体的解决方案来实现这个目标?
答案 0 :(得分:1)
findOne()的回调是异步的,它会在你渲染玉后执行。在用户变量获得新值之前,执行会跳转到“TrackSession”。
你应该把var html = ...放在回调中。
var user = null;
User.findOne({$and: [{"_id": advisorId}, {"role": "advisor"}]},{firstName:1,lastName:1, '_id':0}, function(err,userData,user) {
user = userData;
TrackSession.find({'advisor_id' : advisorId},fields,function(err, chatHistoryData) {
var jade = require('jade');
var html = jade.renderFile(appRoot+'/views/generatePDFHTML.jade', {'chatHistoryData': chatHistoryData,
'selectedOptions':selectedOptions,
'advisor':user,
'tableHeaders':tableHeaders
});
console.log(html); return false;
});
});