I'm facing a weird issue while placing order in my ecommerce. when i place order the 1st time it registers and saves the order in my database but when the same user tries to place order the 2nd time i get a weird error.
my api call -
useEffect(()=>{
const makeRequest = async ()=>{
try{
const res = await userRequest.post("/checkout/pay", {
tokenId:stripeToken.id,
amount: cart.total,
})
try {
userRequest.post('/orders', {
userId: userr._id,
products: cart.products.map((item) => ({
productName: item.title,
productId: item._id,
quantity: item._quantity,
})),
amount: cart.total,
address: res.data.billing_details.address,
})
history('/success');
} catch(err) {
console.log(err)
}
}catch(err){
console.log(err)
}
};
stripeToken && makeRequest();
}, [stripeToken, cart.total, history])
order model -
const mongoose = require('mongoose');
const orderSchema = new mongoose.Schema(
{
userId: {type: String, required: true},
products: [
{
productName: {type: String},
productId: {type: String},
quantity: {type: Number, default: 1},
},
],
amount: {type:Number, required:true},
address: { type: Object, required:true },
status: {type: String, default: 'pending'},
}, {timestamps: true}
);
module.exports = mongoose.model('Order', orderSchema);
order route -
router.post("/", verifyToken, async (req, res) => {
const newOrder = new Order(req.body);
try {
const savedOrder = await newOrder.save();
res.status(200).json(savedOrder);
} catch (err) {
res.status(500).json(err);
}
});
error message when placing order 2nd time__
CodePudding user response:
I think it's happening because backend
creates the same document
again when the same user
places the same order
a second time.
So what you can do is create a function in the backend which checks if the user
has already ordered the same product
then you can just increase
the quantity of the product
in the document for the same user
.
CodePudding user response:
it looks like the problem is that you try to add the same _id twice, in the second time that you want to insert to cart you need to update the order and not make a new one(newOrder.save();) so before you save new order first check if there is a new order if not make newOrder.save() else you need to )update the cart if you using mongoose(findOneAndUpdate)