Андрей _-_ Андрей _-_ - 1 month ago 6x
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://", 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 //


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://", 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.