27
loading...
This website collects cookies to deliver better user experience
I've encountered the issue sometime in my developer path. So I decided to write down my experience and to firstly note to myself and secondly to help other developers/engineers who are a newbie in this topic.
If you only need the fix, you can skip to the last part of this article!
MongoError: E11000 duplicate key error collection: companies index: code_1 dup key: { code: null }
A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space to maintain the index data structure. Indexes are used to quickly locate data without
having to search every row in a database table every time a database table is accessed. Indexes can be created using one or more
columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records.
const userSchema = new Schema(
{
email: {
type: String,
index: true,
unique: true,
},
name: String,
}
);
const companySchema = new Schema(
{
location: String;
name: String,
}
);
MongoError: E11000 duplicate key error collection: companies index: code_1 dup key: { code: null }
companies
collection. And the result was:> db.companies.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "project-name.companies"
},
{
"v" : 2,
"unique" : true,
"key" : {
"code" : 1
},
"name" : "code_1",
"ns" : "project-name.companies",
"background" : true
}
]
code
and it is set to unique. And once an index is set, it is there until you remove it, and the rule unique is still there also.const companySchema = new Schema(
{
code: {
type: String,
index: true,
unique: true,
},
location: String;
name: String,
}
);
> db.companies.dropIndex("code_1")
> db.companies.dropIndexes()
db.companies.getIndexes()