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?

5
  • Can you share all your code? Have you installed and imported mongoose ? Commented Jan 12, 2018 at 23:22
  • 1
    You won't be able to get the value in that way. Have you used promises before? Commented Jan 12, 2018 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. Commented Jan 12, 2018 at 23:25
  • How do I return the response from an asynchronous call? Commented Jan 12, 2018 at 23:29
  • @AlbertoRivera No but I'm researching them now. Commented Jan 12, 2018 at 23:46

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

”very interesting question” - I think you’re confusing “interesting” with “common”.
this worked! thanks.
actually, console.log(result) outputs the result but the employees variable is still undefined :(
The only case the result is undefined is that the function is finished before "return" query. So I think database error is occured before callBack.
The only case the result is undefined is that the function is finished before 'return' query. I think database error is occurred so callBack didn't run. If my answer is correct, will you vote it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.