Py学习  »  MongoDB

如何从MongoDB数据库获取所有文档?

Alexander P • 6 年前 • 901 次点击  

我有一个类,其中包括用于MongoDB连接的Helper方法,包括Connect、FindDocuments和InsertDocument。

async findDocuments(collection, query) {
        var response = await this.database.collection(collection).find(query).toArray();
        return response;
}

console.log(mongo.findDocuments('users', {}));

我希望得到数据库中所有用户的列表。 我正在接受一个承诺。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38673
文章 [ 2 ]  |  最新文章 6 年前
Victor P
Reply   •   1 楼
Victor P    6 年前

find 返回一个光标而不是一个承诺,因此您正确地调用了它。你得到了一个承诺,因为你不在等待寻找文件的电话。

...
async findDocuments(collection, query) {
        var response = await this.database.collection(collection).find(query).toArray();
        return response;
}
...

// await here
console.log(await mongo.findDocuments('users', {}));

这假设您也在异步函数中调用它。

节点驱动程序引用:

http://mongodb.github.io/node-mongodb-native/3.2/api/Collection.html#find

Get Off My Lawn
Reply   •   2 楼
Get Off My Lawn    6 年前

异步函数总是返回一个承诺。要查看承诺信息,您要么需要 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);
});