[英]Why this Map method within Promise.all won't work correctly with MongoDB and Monk in Node.js?
我在Mongo數據庫中有訂單數據。 我在同一數據庫中也有產品信息,因此需要將它們結合起來。
如果訂單有多個產品,則需要為每個產品創建訂單的副本。 因此,如果我對某商品有一個訂單,那么會有兩個相同的訂單,每個商品中都有其中一個。 (數據將以CSV格式提交以提供服務,它將不能在一行數據上接受多個產品)
問題是,當我嘗試從Monk的Mongo數據庫中獲取每個訂單的產品數據時,只有帶有多個項目的每個訂單的一個版本才通過CSV傳遞。
一切都順利進行到decorateProducts函數,這似乎導致訂單丟失。 JSON數組在此之前看起來還不錯,但在此之后缺少訂單。
以下是相關代碼:
...
const decorateProducts = (order) => {
if (typeof order[0] !== 'undefined' && order[0] !== null) {
var prodId = order[0].productId;
return collectionProducts.findOne({"_id": prodId})
.then(currentProduct => {
if (currentProduct) {
var obj = {
"email" : order[0].email,
"firstName" : order[0].firstName,
"lastName" : order[0].lastName,
"location" : order[0].location,
"orderNumber" : order[0].orderNumber,
"orderId" : order[0].orderNumber,
"orderDate" : order[0].orderDate,
"productId" : order[0].productId,
"productTitle" : currentProduct["productTitle"],
"productImageUrl" : currentProduct["productImageUrl"],
"productUrl" : currentProduct["productUrl"]
}
}
else { obj = ""; }
return obj;
})
.catch(err => console.log(err));
}
};
...
collectionOrders.find({})
.then(orders => Promise.all(orders.map(order => processOrder(order))))
.then(orders => Promise.all(orders.map(order => decorateProducts(order))))
.then(orders => writeCsv(orders))
.then(output => res.send(output))
.catch(err => console.log(err));
任何幫助,將不勝感激。
這是因為在decorateProducts
內部,您正在返回一個對象。 嘗試返回一個Promise
以便該對象仍可修復。
const decorateProducts = (order) => {
if (typeof order[0] !== 'undefined' && order[0] !== null) {
var prodId = order[0].productId;
return collectionProducts.findOne({"_id": prodId})
.then(currentProduct => {
if (currentProduct) {
var obj = { /* stuff */ }
}
else { obj = ""; }
return Promise.resolve(obj);
})
.catch(err => console.log(err));
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.