Description:
While trying to save a new document via newModel.save(). I ran into a duplicate key error the second time I tried to insert a new Document in the Collection. The error being,
E11000 duplicate key error collection: mydb.mycollection index: xxxxx.xxxxx_xx_1 dup key: { xxxxx.xxxxx_xx: null }. My schema design is as follows for the value where it errored.
...
xxxxxx: [
{ xxx_xx: {
type: String,
default: "",
unique: true,
},
xxxxxx: {
type: Schema.Types.ObjectId,
ref: "anotherSchema",
}
}
...
Scenario:
newModel.save() works the first time around and the document shows up in the collection viewable by MongoDB Compass. Notice: The collection is empty.
anotherNewModel.save() display's the above error the second time I try to insert the document.
Tried:
Deleted the collection and tried inserting again.
Removed the database and tried again. (Not recommended since you might have more than one collection. Fortunately I had one.)
Checked my schema and nodejs code for mistakes.