Alexander P
Alexander P

Reputation: 33

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.

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.

Upvotes: 0

Views: 83

Answers (2)

Victor P
Victor P

Reputation: 1612

find returns a cursor not a promise so you're calling it correctly. You're getting a promise because you're not awaiting the call to 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

Upvotes: 0

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

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.

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

Upvotes: 1

Related Questions