0

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

furaxsme
  • 23
  • 5

1 Answers1

0

you can do that by updating your createProduct function like so:

const createProduct = async (req, res) => {
    const { name, description, price, stock, categoryId } = req.body;
    const uploadedImages = req.files; // Uploaded images array

    try {
    // ... (same validation and category checks as before)

    // Create product with the given data
    const product = await Product.create({
        name,
        description,
        price: parseFloat(price.replace(",", ".")),
        stock,
        category: category ? categoryId : null,
        slug: slugify(name),
    });

    // Add images to the product
    const imagePromises = uploadedImages.map(async (image) => {
        const newImage = await ImageModel.create({
        imageUrl: image.path, // Assuming multer provides the path
        color: image.color, // Set the color here as needed
        });
        return newImage._id;
    });

    // Wait for all image creation promises to resolve
    const imageIds = await Promise.all(imagePromises);

    // Update the product's images array
    product.images = imageIds;
    await product.save();

    res.json({ product, success: "Produit créé avec succès !" });
    } catch (error) {
    console.log("Error in createProduct", error);
    res.status(500).json({ error: "Une erreur est survenue lors de la création du produit" });
    }
};
Mohamed Mostafa
  • 520
  • 2
  • 10
  • Hi ! Thank you for your answer that seems to be what I want, however sorry I'm a little bit lost but if I want to test directly on POSTMAN if it works how I should go about it I don't know what to put in the key for color, I know that for image it's imageUrl, after the rest I don't really know. THANKS :) – furaxsme Aug 07 '23 at 17:13