Андрей _-_ Андрей _-_ - 3 months ago 20
Javascript Question

use string out of a mongodb function

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 //
}

Answer

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.