Okay, So I managed to fix it & here how I did it.
Why is this error happening?
From their documentation:
A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields.
&
MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.
The reason simply being you are having unique: true
for a field that is contained in an array. MongoDB build's index's for each unique feild. If you have'nt initialized it while saving the document. MongoDB assigns a null value. On saving the other document which also does'nt contain the unique field value. MongoDB tries to assign it null again which fails as unique was set to true and there is already a document with null value. Example: Assume the Schema follow's this pattern.
...
uuid: {
type: String,
unique: true,
}
...
If you create a Document, MongoDB will assign it an index 0 and give it null if there is no value. and If you create another, MongoDB will assign it an index 1 and try to again assign null if there is no value present. The insertion fails as it is supposed to be unique and there is already a null value for first document.
This is fairly visible if you query index's in mongosh shell via. db.getCollection("yourCollection").getIndexes()
...
{
v: 2,
key: { 'xxxxxxx.xxxxxx_xx': 1 },
name: 'xxxxxxx.xxxxxx_xx_1',
background: true,
unique: true
}
]
...
Fix:
The above error can simply be fixed by following simple steps.
- Remove the
unique: true
from the array's in your Schema if you are not creating the newModel with that unique field value.
Note: It only works if you have a unique value that needs to be inserted. Empty (i.e. null) initializations would'nt work and raise this error.
- Open
mongosh
shell via Terminal or Command Prompt.
- Delete any previous entires in the collection you're trying to insert the document in.
- Run
use yourDb
and then db.getCollection("yourCollection").getIndexes()
to check if index's exist. If yes, drop them via db.getCollection("yourCollection").dropIndexes()
.
*Note: You can also drop the entire collection.
- Now restart your NodeJS server if you're using node to access the database.
Goodluck! Happy Creating.