I am facing an issue with my Typescript async method used to query a MongoDB database using the nodejs driver. The compiler seems to be indicating that the "await" before "myConnectedClient" has no effect on the type of this expression. This has left me confused - is the call to the aggregate() method asynchronous? Do I need to wait for it or not?
Thank you.
async findQuery<T>(
collection: string,
findParams: Query<T>,
sort: Sort<T>,
myConnectedClient: MongoClient
) {
const firstResult = await myConnectedClient // the compiler indicates await is useless
.db("ZZZ_TEST_ALL")
.collection("my_collection_01")
.aggregate<string>([{ $project: { _id: 0, name: 1 } }]);
firstResult.forEach((field) => {
console.log(`Field: ${field}`);
});
}
UPDATE: I have discovered that I need to add .toArray() after calling the .aggregate() method; but why exactly is this required? Can someone please explain the underlying mechanism to me? Does aggregate() not have a callback and does it not return a promise? Are there any alternatives to using .toArray()? Thank you.
// now await is functioning correctly
const firstResult = await myConnectedClient
.db("ZZZ_TEST_ALL")
.collection("my_collection_01")
.aggregate<string>([{ $project: { _id: 0, name: 1 } }]).toArray();