skip to Main Content

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 body

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
enter image description here

Tried mongo shell also but getting the same error
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    I am really grateful to Doug Duncan from the MongoDB community who helped me in figuring out the problem.

    So the actual issue as described by Dough was that apparently, I was having a title field with a unique index that was being populated every time I was inserting a new document. Now for the first index, everything was fine and the document got inserted successfully but after that, all the inserts were throwing this title field null error shown below:

    enter image description here

    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. You have a unique index on the title based on the error you’re getting. Run db.products.getIndexes() and you should see the index.

    Ironically, I haven't inserted any field named "title" anytime in my product schema, so how does this happen?

    It turns out that 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 this can be fixed by dropping that index everything should be good and you will be able to insert more than a single document without the duplicate key violation.

    So I ran the db.products.getIndexes() command in the mongo shell and found that he was right, there was actually a "title" field with a unique index value. enter image description here

    According to Dough, this can be fixed by removing the title field using this command
    db.products.dropIndex({"title": 1}) Thanks to Dough, after running this command I can insert multiple documents since the title field is removed now and the only unique index is productId, which I make sure is always unique during insertion.

    More about dropIndex - https://www.mongodb.com/docs/v4.4/reference/method/db.collection.dropIndex/?_ga=2.253559119.714913216.1662801611-1986988651.1652705652


  2. The error indicates an entry with {title: null} already exists for the index title_1. It is most likely a unique index and you need to adjust the title if entry item is a variant under the same title.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search