0

need some help with node js and mongodb how can I return the resp? cause now it returns "undefined";

function(table, where, to_select) {
  var r = {};
  MongoClient.connect("mongodb://127.0.0.1:27017/db", function(err, db) {
    if(!err) {
      collection = db.collection(table);
      collection.find(where, to_select).toArray(function(err, resp) {
        r.t = resp; // return THIS
      });
    }
  });
  return r.t; //returns undefined //
}

2 Answers 2

1

You need to use callback because DB query in asynchronous operation. So your return gets called before find actually return results. Here is the fix

function runQuery(table,where,to_select, callback){ MongoClient.connect("mongodb://127.0.0.1:27017/db", function(err, db) { if (err) {return callback(err);} collection = db.collection(table); collection.find(where,to_select).toArray(function(err, resp) { callback(err, resp); }); }); }

And to call function you need

runQuery(table, where, select, function(err, results){
   ///do something with results.
});

Hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

getting "call back is not a function"
You sure that you run as we told you.. Callback it's just a name of callback function. All should work if you copy code directly. Look at runQuery example
I even simplify a little bit more.
1

MongoClient.connect & collection.find are asynchronous functions. To get value of resp properly you can make getData function asynchronous as below.

function getData(table, where, to_select, callback) { // We pass callback function 
    var r = {};
    MongoClient.connect("mongodb://127.0.0.1:27017/db", function(err, db) {
        if (!err) {
            collection = db.collection(table);
            collection.find(where, to_select).toArray(function(err, resp) {
             // r.t = resp; no need to assign as you want resp only
             callback(err,resp); // return resp
            })
        }else
           callback(err);// return with error 
    });
    //return r.t; r.t will be undefined as r.t is not updated yet, so we can remove this
}


/*Now you can call as below
  getData(whatever,)whatever,whatever,function(err,resp){
      console.log(resp);// You will get result here
  })*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.