如何在 mongodb 聚合中匹配查询后获取数组
how can i get an array after match query in mongodb aggregation
我正在学习节点 js 和 mongodb,我有一个餐厅模式和一个订单模式,每个对象中都有 restaurantId。我在 mongodb 聚合中使用匹配查询来获取一些 restaurantId 等于 "restaurantId" 的订单,但问题是结果是一个承诺,我想将其更改为一个对象数组以轻松操作它.那么有人可以帮助我吗?
这是代码:
const orders = await Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
我想在订单上使用 foreach 函数和其他数组函数,但我不能,因为结果是一个承诺,
谢谢。
首先,让我指出,对于如此简单的查询,甚至不需要使用聚合。您可以使用普通的旧 find
.
话虽如此,在您提供的具体示例中,由于聚合查询前面存在 await
,orders
变量实际上将是匹配订单的数组。只要您 运行 该代码位于 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.
}
另一种 运行 您的代码没有 async
s 和 await
s 的方法是使用 then
。示例:
const somefunc = () => {
Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
.then(orders => console.log(orders))
.catch(e => console.log("error:", e))
}
所以你肯定是正确的 Order.aggregate([...])
returns 一个承诺。但是您可以使用 await
来解决它,您已经这样做了,或者使用上面指出的 then
。
我正在学习节点 js 和 mongodb,我有一个餐厅模式和一个订单模式,每个对象中都有 restaurantId。我在 mongodb 聚合中使用匹配查询来获取一些 restaurantId 等于 "restaurantId" 的订单,但问题是结果是一个承诺,我想将其更改为一个对象数组以轻松操作它.那么有人可以帮助我吗? 这是代码:
const orders = await Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
我想在订单上使用 foreach 函数和其他数组函数,但我不能,因为结果是一个承诺, 谢谢。
首先,让我指出,对于如此简单的查询,甚至不需要使用聚合。您可以使用普通的旧 find
.
话虽如此,在您提供的具体示例中,由于聚合查询前面存在 await
,orders
变量实际上将是匹配订单的数组。只要您 运行 该代码位于 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.
}
另一种 运行 您的代码没有 async
s 和 await
s 的方法是使用 then
。示例:
const somefunc = () => {
Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
.then(orders => console.log(orders))
.catch(e => console.log("error:", e))
}
所以你肯定是正确的 Order.aggregate([...])
returns 一个承诺。但是您可以使用 await
来解决它,您已经这样做了,或者使用上面指出的 then
。