1

i am trying to fetch the result from the database using a function but it is showing that undefined but when i am printing the result in the same method it is printing .. i got to know the reason that node js executing in async but i dont know how to over come this issue

var mongo=require('../routes/mongo')

exports.search=function(userid){
    // console.log(userid)

    mongo.get().collection("customers").find({"userid":userid}).toArray(function(err, result) {

        if (err) throw err;

        // console.log(result)

        return result;


    });


}

when i am printing this in some other module it is printing undefined

it tried to print using this console.log(dboperations.search(req.body.userid))

vamsi reddy
  • 143
  • 10

1 Answers1

1

Because doing database operations is async you can't get the result as sync. You could use a callback.

var mongo=require('../routes/mongo')

exports.search=function(userid, callback){
    // console.log(userid)

    mongo.get().collection("customers").find({"userid":userid}).toArray(function(err, result) {

        if (err) throw err;

        // console.log(result)

        callback(result)
    });
}

And then call the function like

dboperations.search('id of the user', function (result) {
    console.log(result)
})

A nice article about async programming https://blog.risingstack.com/node-hero-async-programming-in-node-js/

Hendry
  • 882
  • 1
  • 11
  • 27