I already have a Product table and an Image Table :
const mongoose = require("mongoose");
const { Schema } = mongoose;
const ProductSchema = new Schema(
{
name: { type: String, required: true },
description: { type: String },
price: { type: Number, required: true },
stock: { type: Number, default: 0, required: true },
slug: { type: String, unique: true },
// images: { type: Array, required: true },
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
},
images: [{ type: mongoose.Schema.Types.ObjectId, ref: "Image" }],
},
{
timestamps: true,
}
);
const ProductModel = mongoose.model("Product", ProductSchema);
module.exports = ProductModel;
const mongoose = require("mongoose");
const { Schema } = mongoose;
const ImageSchema = new Schema({
imageUrl: String,
color: String,
});
const ImageModel = mongoose.model("Image", ImageSchema);
module.exports = ImageModel;
I would like to set up in this function the fact of being able to add one or more images which for each image there is an associated color, because then on the client side I want that when a user chooses a product color that the associated image has the color displayed
const createProduct = async (req, res) => {
const { name, description, price, stock, categoryId } = req.body;
try {
let category;
const validateField = (fieldName) => {
if (!req.body[fieldName]) {
return res.json({ error: `Le champ ${fieldName} est obligatoire` });
}
};
validateField("name");
validateField("price");
validateField("stock");
if (req.fileFilterError) {
return res.json({ error: req.fileFilterError });
}
// Check if slug exist
const exist = await Product.findOne({ slug: slugify(name) });
if (exist) {
return res.json({
error: "Veuillez fournir un nom de produit différent.",
});
}
if (categoryId) {
category = await Category.findById(categoryId);
if (!category) {
return res.json({ error: "La catégorie n'existe pas" });
}
}
const product = await Product.create({
name,
description,
price: parseFloat(price.replace(",", ".")),
stock,
category: category ? categoryId : null,
slug: slugify(name),
});
res.json({ product, success: "Produit créé avec succès !" });
} catch (error) {
console.log("Error in createProduct", error);
}
};
Here is my route :
// CREATE
router.post("/", upload.array("imageUrl", 6), createProduct);
hoping someone can help me thank you