Pet*_* D. 2 javascript mongodb node.js
尽管我发现了与我类似的问题,但我无法独自解决问题。
在我的“ ../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
};
Run Code Online (Sandbox Code Playgroud)
我还注意到,“ console.log(test)”位于“ console.log(docs)”之前。我尝试将'docs'参数作为函数参数传递给'find',但没有结果。
最好的方法是使用Promises。像这样做。
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)
})
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7233 次 |
| 最近记录: |