3
function getEmployees(jobID){
    MongoClient.connect(url, function(err, db){
        if(err) throw err;
        var dbo = db.db("mydb");
        dbo.collection("employees").find({employee:jobID}).toArray(function(err, result){
            if(err) throw err;
            db.close();
            console.log(result) // shows the employees. cool!
            // how do I return result??
        })
    })
}
var employees = getEmpoyees(12345);  // I want the employees variable to be an array of employees

I'm new to node.js and javascript and I can't figure this out. Do I need to implement a callback to use the data the way I'm trying to?

maggotbrain
  • 69
  • 2
  • 4
  • Can you share all your code? Have you installed and imported `mongoose` ? – Chef1075 Jan 12 '18 at 23:22
  • 1
    You won't be able to get the value in that way. Have you used promises before? – Alberto Rivera Jan 12 '18 at 23:24
  • 1
    *”Do I need to implement a callback to use the data the way I’m trying to?”* - yes, or better still go learn about Promises (MongoDB uses them out the box). Promises work particularly well with `async` / `await`. – James Jan 12 '18 at 23:25
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – t.niese Jan 12 '18 at 23:29
  • @AlbertoRivera No but I'm researching them now. – maggotbrain Jan 12 '18 at 23:46

1 Answers1

4

Very interesting question. In this case, you can't return value directly. So I implemented indirect way to get the return value. For this, I added "callback" function as the function parameter in "getEmployees" function. The updated code is as follows.

function getEmployees(jobID, callBack){
MongoClient.connect(url, function(err, db){
    if(err) throw err;
    var dbo = db.db("mydb");
    dbo.collection("employees").find({employee:jobID}).toArray(function(err, result){
        if(err) throw err;
        db.close();
        console.log(result) // shows the employees. cool!
        // you can return result using callback parameter
        return callBack(result);
    })
})
}
var employees = getEmpoyees(12345, function(result) {
   console.log(result);
});  // I want the employees variable to be an array of employees