Javascript Node.js MongoDB collection.find().toArray不返回任何内容
虽然我发现了与我类似的问题,但我无法独自解决这个问题 在我的“../models/user”模型中,我希望找到所有用户并将其放入数组,然后将该数组返回给控制器(我将在其中使用该信息) 这是我的密码:Javascript Node.js MongoDB collection.find().toArray不返回任何内容,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,虽然我发现了与我类似的问题,但我无法独自解决这个问题 在我的“../models/user”模型中,我希望找到所有用户并将其放入数组,然后将该数组返回给控制器(我将在其中使用该信息) 这是我的密码: var mongoDatabase = require('../db'); var database = mongoDatabase.getDb(); function find() { var test; database.collection("customers").find
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)
})
})
}
从MongoDB的文档判断,您不能将参数传递给toArray,为什么不直接执行
test=database.customers.find().toArray()
@Ozan stillundefined@Petar我刚刚在我的本地开发中进行了测试,它确实返回了所有的文档。我不确定是什么原因造成的。为什么不使用mongoose?@Ozan我很快就要开始使用mongoose了,但首先我想学习一些基本知识,你可以试试这个,var mongoDatabase=require(“../db”);var database=mongoDatabase.getDb();函数find(){return database.collection(“customers”).find().toArray();}module.exports={find};我应该包括哪些模块?这是“jQuery”吗?不,我已经编辑过了,你应该安装一个npm模块“q”。没有必要再添加一个模块,因为Node.js从0.12版开始就支持本机承诺。谢谢你指出这一点。我已经编辑了我的答案。@PetarD。如果不想包含该模块,也可以使用上述代码