[英]Assign mongoose return result to node js variable
I am new to node js and mongoose.I have the below code in node js. 我是node js和mongoose的新手,我在node js中有以下代码。 I wanted to assign the return userData
record by the mongoose to variable user
which is outside the callback. 我想通过猫鼬将返回的userData
记录分配给回调之外的变量user
。
var user = null;
User.findOne({$and: [{"_id": advisorId}, {"role": "advisor"}]}, {firstName:1,lastName:1, '_id':0},
function(err,userData) {
user = userData;
});
Once I have the return result in user
variable I can directly pass it to the jade view as follow: 一旦在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;
});
But when I am trying to do this I am getting null
as the value of the user
variable. 但是,当我尝试执行此操作时,我将得到null
作为user
变量的值。 Is there any specific solution to achieve this? 有什么具体解决方案可以实现这一目标吗?
The callback of the findOne() is asynchronous, it gets executed after you get to rendering the jade. findOne()的回调是异步的,在渲染玉器之后将执行该回调。 The execution jumps to "TrackSession" before the user variable gets a new value. 用户变量获得新值之前,执行跳至“ TrackSession”。
You should put the var html = ... inside the callback. 您应该将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; }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.