【发布时间】:2017-07-15 13:51:20
【问题描述】:
虽然我发现了与我类似的问题,但我无法自己解决问题。
在我的“../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”,但没有结果。
【问题讨论】:
-
从 MongoDB 的文档来看,你不能将参数传递给 toArray 为什么不干脆做
test = database.customers.find().toArray() -
@Ozan 仍未定义
-
@Petar D. 我刚刚在本地开发中进行了测试,它确实返回了所有文件。我不确定是什么原因造成的。你为什么不使用猫鼬?
-
@Ozan 我很快就会开始使用 Mongoose,但首先我想学习基础知识
-
你可以试试这个,var mongoDatabase = require('../db'); var 数据库 = mongoDatabase.getDb(); function find() { return database.collection("customers").find().toArray(); } module.exports = { 查找 };
标签: javascript node.js mongodb