虽然我发现了和我类似的问题,但我自己也解决不了问题。
在我的'../models/user'模型中,我希望找到所有用户并将其放入数组,然后将该数组返回给控制器(在那里我将使用信息)。
下面是我的代码:
var mongoDatabase = require('../db');
var database = mongoDatabase.getDb();
function find() {
var test;
database.collection("customers").find().toArray( function(err, docs) {
if(err) throw err;
console.log(docs); //works fine
//I'd like to return docs array to the caller
test = docs;
});
console.log(test); //test is undefined
}
module.exports = {
find
};
我还注意到,'console.log(test)'在'console.log(docs)'之前。我尝试将'docs'参数作为函数参数传递给'find',但没有结果。
最好的办法就是用承诺。这样做。
function getUsers () {
return new Promise(function(resolve, reject) {
database.collection("customers").find().toArray( function(err, docs) {
if (err) {
// Reject the Promise with an error
return reject(err)
}
// Resolve (or fulfill) the promise with data
return resolve(docs)
})
})
}