简体   繁体   English

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

[英]How would i get all documents form a mongodb database?

I have a class that includes helper methods for my MongoDB Connection, including connect, findDocuments and insertDocument. 我有一个类,其中包含用于MongoDB Connection的辅助方法,包括connect,findDocuments和insertDocument。

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

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

I expected to get a list of all the users in my database. 我希望获得数据库中所有用户的列表。 I am receiving a Promise. 我收到一个诺言。

Async functions always return a promise. 异步函数总是返回一个承诺。 To see the promise information, you either need to await the result if you are in a function, or use a then() if you are in the global scope. 要查看承诺信息,如果您在函数中,则需要await结果,或者,如果您在全局范围内,则需要使用then()

Your code looks like it is in the global scope so you will need to use a 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);
});

find returns a cursor not a promise so you're calling it correctly. find返回的游标不是promise,因此您可以正确调用它。 You're getting a promise because you're not awaiting the call to findDocuments. 您得到了诺言,因为您没有等待对findDocuments的调用。

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

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

This is assuming you're calling this inside an async function as well. 假设您也在异步函数中调用此函数。

Node driver reference: 节点驱动程序参考:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM