I cannot implement the logic to update my product stocks at my Back interface after an order placed via my website (Customer).
I would simply like that after an order for products made via the Site, the stocks of the products ordered decrease by the quantity ordered.
Here are the relative files present in my code:
** Models / Order :
import {model, models, Schema} from "mongoose";
const OrderSchema = new Schema({
line_items:Object,
name:String,
email:String,
city:String,
zip:String,
address:String,
country:String,
paid:Boolean,
}, {
timestamps: true,
});
export const Order = models?.Order || model('Order', OrderSchema);
** Model / Product :
import mongoose, {model, Schema, models} from "mongoose";
const ProductSchema = new Schema({
title: {type:String, required:true},
description: {type:String, required:true},
price: {type: Number, required: true},
details: {type:String},
brand: {type:String},
stock: {type:Number},
sizes: {type:String},
gender: {type:String},
images: [{type: String}],
category: {type:mongoose.Types.ObjectId, ref:'Category'},
});
export const Product = models.Product || model('Product', ProductSchema);
Api / Order :
import { mongooseConnect } from "@/lib/mongoose";
import { Order } from "@/models/Order";
import { Product } from "@/models/Product"; // Importez le modèle de produit
export default async function handler(req, res) {
await mongooseConnect();
// Ajoutez votre logique pour enregistrer une nouvelle commande
if (req.method === 'POST') {
const { line_items } = req.body;
try {
const newOrder = await Order.create(req.body);
for (const item of line_items) {
const { product_id, quantity } = item;
const product = await Product.findById(product_id);
product.stock -= quantity;
await product.save();
}
res.status(201).json(newOrder);
} catch (error) {
console.error("Error creating order:", error);
res.status(500).json({ error: "Internal server error" });
}
} else {
const orders = await Order.find().sort({ createdAt: -1 });
res.status(200).json(orders);
}
}
Api/ Products :
import { mongooseConnect } from '@/lib/mongoose';
import { Product } from '@/models/Product';
export default async function handle(req, res) {
const { method } = req;
await mongooseConnect();
if (method === 'POST') {
const { title, description, price, images, category,details, brand, gender, sizes, stock } = req.body;
const productDoc = await Product.create({
title,
description,
price,
images,
category,
details,
brand, gender, sizes, stock
})
res.json(productDoc);
}
if (method === 'GET') {
if (req.query?.id) {
res.json(await Product.findOne({ _id: req.query.id }));
} else {
res.json(await Product.find());
}
}
if (method === 'PUT') {
const { title, description, price, _id, images, category,details, brand, gender, sizes, stock } = req.body;
await Product.updateOne({ _id }, {
title, description, price, images, category,details, brand, gender, sizes, stock
});
res.json(true);
}
if (method === 'DELETE') {
if (req.query?.id) {
await Product.deleteOne({_id:req.query?.id});
res.json(true)
}
}
}
Database :
enter image description here
enter image description here
I tried to do this but nothing is updated, neither in the Database nor at the interface level :
import { mongooseConnect } from '@/lib/mongoose';
import { Product } from '@/models/Product';
export default async function handle(req, res) {
const { method } = req;
await mongooseConnect();
if (method === 'POST') {
const { line_items } = req.body;
try {
const newOrder = await Order.create(req.body);
for (const item of line_items) {
const { product_id, quantity } = item;
await Product.updateOne(
{ _id: product_id },
{ $inc: { stock: -quantity } }
);
}
res.status(201).json(newOrder);
} catch (error) {
console.error("Error creating order:", error);
res.status(500).json({ error: "Internal server error" });
}
}
// Autres routes GET, PUT, DELETE...
}