0

I have these mongoose schema

var subCategory = new Schema({
name : {
        type: String
      },
description : {
        type : String
      }
});

var CategorySchema = new Schema({
    name: {
    type: String,
    required: true,
    unique : true,
    sparse: true
   },
   description : {
    type: String
   },
   subCategory : [subCategory]
});

When I try to insert second document I get duplicate error as follows :

insertDocument :: caused by :: 11000 E11000 duplicate key error index: phychometric_database.categories.$category_1 dup key: { : null }

To best of my knowledge this is because there is already a document with null value at one of indexed path. But I am passing a value to 'name' path in the document as follows.

var newCategory = new Category.Categories({
            name: req.body.name,
            description: req.body.description
          });
          // save the user
          newCategory.save(function(err) {
            if (err) {
                console.log(err);
                return res.json({success: false, msg: 'Category already exists.'});
            }
            res.json({success: true, msg: 'Successful created new category.'});
          });

Can anyone explain?

utkarsh sharma
  • 149
  • 2
  • 12
  • It looks like you initially had a property called `category` in your schema, that had a non-sparse unique index. If so, you need to remove that index. See also [this question](http://stackoverflow.com/questions/15029157/using-sparse-true-still-getting-mongoerror-e11000-duplicate-key-error). – robertklep Jun 25 '16 at 20:10
  • @robertklep, Thanks that fixed my problem. – utkarsh sharma Jun 25 '16 at 20:39

0 Answers0