2016-08-28 2 views
0

ノードjsとmongodbの助けが必要 どのように私はrespを返すことができますか?現在は "undefined"を返します。mongodb関数の文字列を使用する

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

答えて

1

非同期操作でのDBクエリのためにコールバックを使用する必要があります。実際に結果を返す前に戻り値が呼び出されます。ここでは、

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

を必要とする修正

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); }); }); }

と機能を呼び出すためには、この情報がお役に立てば幸いです。

+0

「コールバックは関数ではありません」 –

+0

あなたは私たちに言ったように実行してください。コールバックは単なるコールバック関数の名前です。コードを直接コピーする場合は、すべてが動作するはずです。 runQueryの例である –

+0

を見てみると、少し単純化さえしています。 –

1

MongoClient.connect & collection.findasynchronous機能です。 respの値を正しく取得するには、getDataの機能asynchronousを以下のように正しく設定することができます。

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 
    })*/ 
+0

ありがとうございます) –

関連する問題