{"index": 0,"code": 11000,"keyPattern": {"Name": 1}, "keyValue": { "Name": null }} error on adding second product to database

Issue

On trying to add a product to my database using the following method,

//ADD PRODUCT
router.post("/addproduct", verifyTokenAndAdmin, async (req, res) => {
  const newProduct = new Product(req.body);

  try {
    console.log("req for pdt add");
    const savedProduct = await newProduct.save();
    console.log("pdt added successfully");
    res.status(200).json(savedProduct);
  } catch (err) {
    res.status(500).json(err);
  }
});

Mongoose is throwing this error when adding the second product. The first product is successful always but cannot make a second post request and also put request to update the product details is not working, but the delete request works perfectly fine

{
    "index": 0,
    "code": 11000,
    "keyPattern": {
        "Name": 1
    },
    "keyValue": {
        "Name": null
    }
}

Given below is my product schema

const { default: mongoose } = require("mongoose");

const ProductSchema = new mongoose.Schema(
  {
    title: { type: String, required: true, unique: true },
    desc: { type: String, required: true },
    img: { type: String, required: true },
    category: { type: Array, required: true },
    size: { type: String },
    color: { type: String },
    price: { type: Number, required: true },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Product", ProductSchema);

Solution

Because in your MongoDB field "name" have Properties UNIQUE at the field "Indexes". And you have to drop that property or you never can create the same name value even if it a empty value.

I used to have the same error, and this is my resolution for the issue:

p/s: Sorry if my English is bad, so if anyone else can translate from Eng -> Eng with more easier to read.. please help me LOLL.
Because my English is bad so… see this img for more understand what the hell Im saying.

Answered By – Tin Hung Le

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published