简体   繁体   中英

Assign mongoose return result to node js variable

I am new to node js and mongoose.I have the below code in node js. I wanted to assign the return userData record by the mongoose to variable user which is outside the callback.

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:

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. 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. The execution jumps to "TrackSession" before the user variable gets a new value.

You should put the var html = ... inside the callback.

 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; }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM