需要一些关于 Node js 和 mongodb 的帮助 我怎样才能返回resp?因为现在它返回“未定义”;
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 //
}
最佳答案
由于数据库查询是异步操作,因此需要使用回调。因此,您的 return 在 find 实际返回结果之前被调用。这是修复方法
函数 runQuery(表、where、to_select、回调){
MongoClient.connect("mongodb://127.0.0.1:27017/db", 函数(err, db) {
if (err) {返回回调(err);}
集合 = db.collection(表);
collection.find(where,to_select).toArray(function(err, resp) {
回调(错误,响应);
});
});
}
并调用您需要的函数
runQuery(table, where, select, function(err, results){
///do something with results.
});
希望这有帮助。
关于javascript - 使用 mongodb 函数中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188918/