【问题标题】:how can i get an array after match query in mongodb aggregation如何在 mongodb 聚合中获取匹配查询后的数组
【发布时间】:2021-06-18 14:02:34
【问题描述】:
我正在学习节点 js 和 mongodb,我有一个餐厅模式和一个订单模式,每个对象中都有 restaurantId。我在 mongodb 聚合中使用匹配查询来获取一些餐厅 ID 等于 "restaurantId" 的订单,但问题是结果是一个承诺,我想将其更改为对象数组以轻松操作它。那么任何人都可以帮助我吗?
这是代码:
const orders = await Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
我想在订单上使用 foreach 函数和其他数组函数,但我不能,因为结果是一个承诺,
谢谢。
【问题讨论】:
标签:
node.js
mongodb
aggregation-framework
match
mongoose-schema
【解决方案1】:
首先,让我指出,对于这么简单的查询,甚至不需要使用聚合。您可以使用普通的旧 find 进行设置。
话虽如此,在您提供的具体示例中,orders 变量实际上是匹配订单的数组,因为在聚合查询前面存在await。只要您在async 函数中运行该代码,该代码就应该可以正常工作。示例:
const somefunc = async () => {
const orders = await Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
]);
console.log(orders); //will print an array of orders or [] if no orders are found.
}
在没有asyncs 和awaits 的情况下运行代码的另一种方法是使用then。示例:
const somefunc = () => {
Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
.then(orders => console.log(orders))
.catch(e => console.log("error:", e))
}
所以你肯定是正确的,Order.aggregate([...]) 返回了一个承诺。但是您可以使用您已经使用的await 或上面指出的then 来解决它。