需要一些节点js和mongodb的帮助 我该怎么回复?因为它现在返回" undefined&#34 ;;
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 //
}
答案 0 :(得分:1)
MongoClient.connect
& collection.find
是asynchronous
个函数。
要正确获得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
})*/
答案 1 :(得分:1)
您需要使用回调,因为异步操作中的DB查询。所以在查找实际返回结果之前会调用您的返回。这是修复
beforeConnect: function(handshake, cb) {
if (handshake.headers.cookie) {
console.log(handshake);
// TODO: check session authorization
} else {
return cb(null, false);
}
return cb(null, true);
},
要调用你需要的功能
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);
});
});
}
希望这有帮助。