我有一个类,其中包含 MongoDB 连接的辅助方法,包括 connect、findDocuments 和 insertDocument。
async findDocuments(collection, query) {
var response = await this.database.collection(collection).find(query).toArray();
return response;
}
console.log(mongo.findDocuments('users', {}));
我希望获得数据库中所有用户的列表。 我收到了一个 promise 。
最佳答案
异步函数总是返回一个 promise 。要查看 promise 信息,您需要 await
如果您在函数中,或者使用 then()
则结果如果您在全局范围内。
您的代码看起来像是在全局范围内,因此您需要使用 then:
class Mongo {
async findDocuments(collection, query) {
var response = (await this.database.collection(collection).find(query)).toArray();
return response;
}
}
let mongo = new Mongo();
mongo.findDocuments('users', {}).then(result => {
console.log(result);
});
关于javascript - 我如何从 mongodb 数据库获取所有文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57634382/