0

I am trying to get the value of the find() function outside the callback function but whenever i try to query it, the variable is undefined.

var _ = require('lodash');

app.get('/',function(req,res){
    var start = parseInt(req.query.start);
    var end = parseInt(req.query.end);
    var dept = parseInt(req.query.dept);
    var resultArray = [];
    database.collection("emp").find({"eid" : {$gte : start, $lte : end},"depid" : dept}).toArray(function(err,result){
     resultArray = result;
    });
    console.log(resultArray);
    var deptArray = [];
    _(resultArray).forEach(function(element){
        var a = database.collection("dept").findOne({"depid" : element.depid});
        deptArray.push(a);
    });     
    res.send(deptArray);

The following statement is giving me undefined :

console.log(resultArray);

I have tried implementing the different answers on stackoverflow but to no avail, I'm still getting not defined outside the scope. I also read something about Promises but I wasn't able to implement them because I'm very new to javascript and node right now. Any help would be highly appreciated.

EDIT :

I dabbled around and got a working solution but I don't know if it's the best way to do it. My requirements in the database queries had changed a bit so please don't mind any changes to the queries.

app.get('/emprecords',function(req,res){
    var start = parseInt(req.query.start);
    var end = parseInt(req.query.end);
    async.parallel([
        function (callback){
            database.collection('dept').find({ "active": "Y"}).toArray(function (err, results) {
                return callback(err, results);
            });
        },
        function(callback){
            var deptArray = []
            database.collection("dept").find({"active" : "Y"}).toArray(function(err,results){
                _(results).forEach(function(element){
                    deptArray.push(element.depid);
                });
                return callback(err,deptArray);
            });
        }
    ], function (err, results) {
        if (err) {
            // @todo: handle the error
        }
        var finalArray = [];
        database.collection("emp").find({ "eid": { $gte: start, $lte: end },"depid" : { $in : results[1]}}).toArray()
        .then(function(result){
            _(result).forEach(function(element){
               finalArray.push({
                   "ename" : element["ename"],
                   "desc" : _.find(results[0],{depid : element.depid}).desc,
                   "salary" : element.salary,
                   "salary5%" : element.salary*1.05

               })

            });
            res.send(finalArray);

        });


    });
});  

0 Answers0