【发布时间】:2018-06-10 11:12:08
【问题描述】:
我有以下代码来查询 MongoDB 数据库:
var docs;
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
findDocuments(db, function() {
console.log(docs);
client.close();
});
});
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('oee');
// Find some documents
collection.find(query).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
//console.log(docs);
callback(docs);
return docs;
});
};
}
哪些输出:
Connected successfully to server
Found the following records
undefined
我想使用存储在变量 docs 中的查询结果进行进一步处理。但是,它们不会从函数中返回。即表达式
findDocuments(db, function() {
console.log(docs);
client.close();
});
我得到一个“未定义”返回。我做错了什么?
【问题讨论】:
标签: javascript node.js mongodb return hoisting