module.exports.checkoutMany = async (data) => { let tempTotalAmount = 0
data.orderDetail.forEach(async e => {
let price = await Product.findById(e.productId).then(product => {
console.log(`product price from forEach: ${product.price}`)
return product.price
})
console.log(`price * quantity: ${price} * ${e.quantity}`)
tempTotalAmount += price * e.quantity
console.log(`tempTotalAmount: ${tempTotalAmount}`)
})
// let newOrderDetail = data.orderDetail.map(async obj => {
// if(obj.keys === price) {
// return obj.price = 1
// } else {
// return obj
// }
// })
// for(i = 0; i < data.orderDetail.length; i++) {
// if(data.orderDetail[i].price) (
// )
// }
console.log('newOrderDetail')
console.log(newOrderDetail)
let newOrder = await new Order ({
userId: data.userId,
orderDetail: data.orderDetail,
totalAmount: tempTotalAmount
})
return newOrder.save().then((order, error) => {
if(error) {
return false
} else {
return order
}
})
}
I tried to get the object property name and assign new value but it did not work.
My objective is to automate the price property by getting it from the Product Model.
As of now it is manually define inside the req.body of Postman.
Thank you.
I think you can accomplish this using Array.map() like you have in your first commented out attempt:
let arr = [
{id: 1, name: "Michael"},
{id: 2, name: "Joe"},
]
const newArr = arr.map(obj => {
if (obj.id === 1) {
return {...obj, name: "John"};
} else {
return obj;
}
});
console.log(newArr);
The way you have it now, you are overwriting the object, not modifying the object when obj.price = 1. You can use the spread operator to fill the new object with all the properties of the previous object, then overwrite the desired property.
You are also using awaits in the wrong places. The map function, and creating newOrder are not async tasks