How can I compute the totalPrice
of specific item, I’m trying to multiply the quantity and the price of specific product
and then POST
it, but I’m having a hard time on how can I compute the totalPrice
of specific item
OrderSchema.js
const OrderSchema = new mongoose.Schema({
userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
products: [
{
productId:{
type: mongoose.Schema.Types.ObjectId, ref: 'Product'
},
quantity: {
type: Number,
default: 1,
},
sellerId: {
type: mongoose.Schema.Types.ObjectId, ref: 'User'
},
totalPrice: {
type: Number,
default: 0,
}
}
],
}, {timestamps: true}
)
export default mongoose.model('Order', OrderSchema)
Order.js
const handleSubmit = async (e) =>{
e.preventDefault()
if(orderSummary?.location === ""){
toast.error("Please input location..")
}else{
try {
await userRequest.post(`/order`,{
userId: currentUser._id,
products: cart.products.map((item) =>({
productId: item._id,
quantity: item.quantity,
sellerId: item.seller_id._id,
totalPrice: Number(item.quantity * item._id.price)
})),
})
} catch (error) {
toast.error("Please put a Location and Time!")
}
}
}
in this image, I want to get the total amount of specific product, so the first product should have a 369
.
But when I call my get all orders, this is what I get
{
"_id": "63b1b4de5a95bd4df7f9443b",
"userId": {
"_id": "63b18af8363f51fa50801dd0",
"studentId": "1234567892"
},
"products": [
{
"productId": {
"_id": "63b16fc58fe585c7b81c748d",
"title": "asd",
"price": "123"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"_id": "63b1b4de5a95bd4df7f9443c"
},
{
"productId": {
"_id": "63b16ff08fe585c7b81c7496",
"title": "asd21",
"price": "213"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"_id": "63b1b4de5a95bd4df7f9443d"
}
],
}
What I’m trying to get here when I call order.js is the totalPrice, like this example.
{
"_id": "63b1b4de5a95bd4df7f9443b",
"userId": {
"_id": "63b18af8363f51fa50801dd0",
"studentId": "1234567892"
},
"products": [
{
"productId": {
"_id": "63b16fc58fe585c7b81c748d",
"title": "asd",
"price": "123"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"totalPrice": "369"
},
{
"productId": {
"_id": "63b16ff08fe585c7b81c7496",
"title": "asd21",
"price": "213"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"totalPrice": "639"
}
],
}