Failed to create product document

Hi everyone,

I hope this is the right place to discuss the CRUD issues. So I’m building a MERN e-commerce app, where I created the mongoose schema and connected with MongoDB to store the products & users. To test my schema and routes I used Postman, and while other requests related to users were working as usual I faced a weird error in the case of adding new products since this is the most important feature.

I’m not sure what is this error and why is this error occurring.
This is my POST request -

const Product = require("../models/Product");
const router = require("express").Router();

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

  try {
    const savedProduct = await newProduct.save();
    res.status(200).json(savedProduct);
  } catch (err) {
    res.status(500).json(err);
  }
});

The verifyToken is a JWT token.

Here is the Schema

const mongoose = require("mongoose");

const ProductSchema = new mongoose.Schema(
    {
        prodId: {
            type: String,
            required: true,  
        },
        prodName: {
            type: String,
            required: true,
        },
        brandName: {
            type: String,
            required: true,
        },
        img: {
            type: Array,
        },
        color: {
            type: Array,
        },
        size: {
            type: Object,
        },
        fabricSpecs: {
            type: String,
        },
        model: {
            type: String,
        },
        descDetail: {
            type: String,
        },
        price: {
            type: Number,
            required: true
        },
        discount: {
            type: Boolean
        },
        discountAmount: {
            type: Number
        },
        rating: {
            type: String
        },
        review: {
            type: Number
        },
        soldOut: {
            type: Boolean
        },
        category: {
            type: String,
        },
        type: {
            type: String,
        }
    },
    {
        timestamps: true,
    }
);

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

Here is the error shown in the Postman while adding creating another product
image

Even doing so with mongo shell I’m getting “duplicate key error”

Hi @sujoy_dutta and welcome to the MongoDB Community forums. :wave:

What I am seeing is that you have a unique index on the title field for the products collection. This is not getting populated so a null value is getting passed to the document and there is already a document with a null value in the collection.

If you are not using title as a field, you can drop that index.

Hey @Doug_Duncan thanks for the reply and it’s nice to be here.

I checked my schema and the JSON object that I’m passing none of them has the title field, I’m not sure how it is getting included since MongoDB inserts _id as default

FYI, the error only occurs from the second insert onwards the first insert works well as expected. Also I forgot to mention I don’t have any unique index in the schema.

This is to be expected as the first insert would not violate a uniqueness constraint.

You have a unique index on title based on the error you’re getting. Run db.products.getIndexes() and you should see the index. It should look similar to the following:

image

Again, if this index is not needed you can safely drop it by running db.products.dropIndex({"title": 1}).

1 Like

And, if I may add, if the index is needed and it has to be unique, you may make it a partial index that exclude null value on title. This way if title is specified uniqueness will be enforced but you will be able to have multiple documents with null title.

2 Likes

Hey thanks a lot @Doug_Duncan I really appreciate your help, your fix worked and now I’m able to add products to the DB. May I ask why these indexes are hidden from the actual JSON object?

It seems like if the error occurs again I will have to drop those indexes.

1 Like

I’m not sure what you mean here. The indexes are hidden from what JSON object?

Ahh sorry, I mean in Postman 200 response message I couldn’t find the title field.

{
    "prodId": "A0WE194R5V",
    "prodName": "Quilted Straight Leg Dungarees",
    "brandName": "Andrea Bogosian",
    "img": [
        "https://i.ibb.co/BPFvmv4/Womens-Dungarees-0006-3-quilted-straight-leg-dungarees.jpg",
        "https://i.ibb.co/LxQc77d/Womens-Dungarees-0007-3a-quilted-straight-leg-dungarees.jpg",
        "https://i.ibb.co/zZF7gjC/Womens-Dungarees-0008-3b-quilted-straight-leg-dungarees.jpg"
    ],
    "color": [
        {
            "hexcode": "#38576c",
            "value": "Blue"
        },
        {
            "hexcode": "#b9c6ca",
            "value": "Silver"
        },
        {
            "hexcode": "#798ea4",
            "value": "Blue"
        }
    ],
    "size": {
        "Standard": [
            "XXS",
            "XS",
            "S",
            "M",
            "L",
            "XL",
            "XXL"
        ],
        "UKsize": [
            "6",
            "8",
            "10",
            "12",
            "14",
            "16",
            "18"
        ],
        "Italysize": [
            "38",
            "40",
            "42",
            "44",
            "46",
            "48",
            "50"
        ]
    },
    "fabricSpecs": "Cotton 100% | logo plaque | adjustable shoulder straps | straight leg | Made in Italy",
    "model": "The model is 1.76 m wearing size 27 (Waist)",
    "descDetail": "Put a spin on those plain dungarees with this pair by Andrea Bogosian. Is it just us, or does the chain strap and quilted flap pocket combo remind you of Chanel’s coveted 2.55 bag?",
    "price": 692.45,
    "discount": true,
    "discountAmount": 10,
    "rating": "4.9",
    "review": 4806,
    "soldOut": false,
    "category": "Denim",
    "prodType": "Dungarees",
    "_id": "631ce678f6ed781219fea5dd",
    "createdAt": "2022-09-10T19:33:12.927Z",
    "updatedAt": "2022-09-10T19:33:12.927Z",
    "__v": 0
}

MongoDB will only return fields that the document has. If there is no title field in the document then there is nothing to show. It’s not hidden, it just simply isn’t there.

MongoDB will allow you to create indexes on fields that don’t exist. It seems that somehow a unique index got created on the title field at some time even though no documents would contain that field. Now that you’ve dropped that index everything should be good and you will be able to insert more than a single document without the duplicate key violation.

1 Like

Thanks a lot @Doug_Duncan for clarifying I know it might be a dumb question to ask but I had this weird confusion.

And again thanks, I’m glad I learned something new

You had a question and you asked. Nothing dumb about that. You had the courage to ask, which can help others out should they have similar questions around this. In the end, you not only helped yourself understand something, but have helped others out as well.

This is what the forums are all about. Learning and sharing knowledge.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.