Alankar More
Alankar More

Reputation: 1115

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?

Upvotes: 0

Views: 962

Answers (1)

Alan Bogu
Alan Bogu

Reputation: 775

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

Upvotes: 1

Related Questions