[英]how can i get an array after match query in mongodb aggregation
我正在學習節點 js 和 mongodb,我在每個 object 中都有一個餐廳模式和一個帶有餐廳 ID 的訂單模式。 我在 mongodb 聚合中使用匹配查詢來獲取一些 restaurantId 等於“restaurantId”的訂單,但問題是結果是 promise,我想將其更改為對象數組以輕松操作它。 那么任何人都可以幫助我嗎? 這是代碼:
const orders = await Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
我想在訂單上使用 foreach function 和其他數組函數,但我不能,因為結果是 promise,謝謝。
首先,讓我指出,對於這么簡單的查詢,甚至不需要使用聚合。 您可以使用普通的舊find
設置 go 。
話雖如此,在您提供的具體示例中,由於在聚合查詢前面存在await
, orders
變量實際上將是匹配訂單的數組。 只要您在async
function 中運行該代碼,該代碼就應該可以正常工作。 例子:
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
和await
的情況下運行代碼的方法是使用then
。 例子:
const somefunc = () => {
Order.aggregate([
{
$match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
}
])
.then(orders => console.log(orders))
.catch(e => console.log("error:", e))
}
所以你肯定是正確的Order.aggregate([...])
返回一個 promise。 但是您可以通過使用await
來解決它,您已經then
做了,或者如上所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.