Document dublication on a single submission

I have a collection that should have a unique value in addition the id, like this

  book: { type: String, unique: true },

```When I check on the db, `book`  is not indexed, so I tried indexing it to ensure there is no value duplication of `book` but I get an error, even on unique values not in the database.

MongoServerError: E11000 duplicate key error collection: test.library index: book_1 dup key: { book: null }

Hello @Caleb_Mucheru

Can you please review your code:

  • are you writing to the collection you want to?
  • it looks as if there is an index on ‘book’
  • also it seems that the duplication is on a ‘null’ value → please verify if you codes does what you want

In case you can not fix the issue by checking the above points, please provide more details.

Best, Michael

I am writing to the collection I want to only when I remove an index on book. But this makes us have a two documents on a single submit, first with some fields, which some are empty and the second one which has all fields as expected.

Hello @Caleb_Mucheru
I am not sure if I understand correct:

  • you do one insert but you end up with two documents
  • when you add an unique index on book then you get the E11000 duplicate key error?

Can you please share your code?

Best, Michael