【发布时间】:2022-01-19 17:20:53
【问题描述】:
我有这个用 Typescript 编写的异步方法来查询,使用 nodejs 驱动程序,一个 MongoDB;编译器指出“myConnectedClient”之前的“await”对这个表达式的类型没有影响;我很困惑:对聚合()的调用是异步的吗?所以,我必须等待吗?
谢谢。
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}`);
});
}
更新:我必须在 .aggregate() 调用之后添加 .toArray();但为什么?任何人都可以解释我的机制吗?聚合()没有回调并且不返回承诺? .toArray() 有替代品吗?谢谢。
// now await it's ok
const firstResult = await myConnectedClient
.db("ZZZ_TEST_ALL")
.collection("my_collection_01")
.aggregate<string>([{ $project: { _id: 0, name: 1 } }]).toArray();
【问题讨论】:
标签: javascript typescript mongodb