user7014817
user7014817

Reputation:

Cannot access db result in Nodejs, it always returns null

 var robject=[]; 
 async.waterfall([
        function (callback) {
            for(var i in serial){
                Router.find({},{r_serial_no:serial[i]},function (err,routerData) {
                    robject = robject.concat(routerData);
                });
            }
            console.log('Robject= '+robject); //THIS RETURNS NULL
            callback(null, robject);
        },
        function (blogs, callback) {
            res.render('index', {dispatched_data:dispatched_data });
            callback(null, 'Ended..' );
        }

    ], function (err, result) {
        console.log(result);
    });

this is my waterfall model, here i need to access the robject from schema.find method to outside of that method. but it always return null.. how to access that??

Upvotes: 1

Views: 55

Answers (2)

Tolsee
Tolsee

Reputation: 1705

The problem I see here is in for...in loop. Your callback will be fired even if your process i.e. Router.find is not completed. You can try below code, It might help.

Unlike your serial object please create a array called serials.

var robject=[]; 
 async.waterfall([
        function (callback) {
            async.each(serials,
              function(serial, localCb){
                Router.find({},{r_serial_no:serial},function (err,routerData) {
                    robject = robject.concat(routerData);
                    localCb()
                });
              },
              function(err){
                console.log('Robject= '+robject); 
                callback(null, robject);
              }
          ); 
        },
        function (blogs, callback) {
            res.render('index', {dispatched_data:dispatched_data });
            callback(null, 'Ended..' );
        }

    ], function (err, result) {
        console.log(result);
    });

Upvotes: 1

Goolishka
Goolishka

Reputation: 240

You have the syntax error:

 for(var i in serial){
                Router.find({},{r_serial_no: i},function (err,routerData) {
                    robject = robject.concat(routerData);
                });
            }

the "for" loop defines "i" as next item in the array each iteration

Upvotes: 1

Related Questions