To be generated id is marked as duplicate

I’m trying to insert multiple data using a for-loop (there will be individual processing after each insertion). The _id for each should be auto-generated so I’m providing null in that field.

I’m getting a E11000 duplicate key error collection: . . . . . . . . dup key: { id: null }

Nothing is inserted.
I’m assuming that the id will be generated before the insertion.
Why is null being flagged as duplicate?

Edit: The same thing happens with insertMany()

If the

you should not supply any values. Null is a value so you should not

The error message does not match part of you post. You write

with an leading underscore but the error complains about

without the leading underscore. Have you redacted the error message? Is it _id or id? The only auto-generated field in native mongo is the top level _id. If you have an error with id rather than _id then you must have a unique index on that field. If you do, then you cannot have 2 documents with the same value and null is a value.

To conclude

  1. Only top level _id is auto-generated
  2. If you want top level _id to be auto-generated, you must not supply a value (and null is a value)

Yeah, I realized that after looking at the indexes. There was an unwanted index probably created from the earlier stages of the code. I should’ve created a reply instead of an edit. Let me mark your reply as the solution though. Thanks for the detailed explanation!

1 Like

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