mongodb error(MongoError: E11000 duplicate key error index)

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

Today, when I was writing mongodb code, I deleted an ID attribute of one schema in the database, and encountered the following error. Later, by clearing the database, the problem was solved, so I want to record the whole process var siteschema = new schema ({
ID: {type: number, unique: true},
Name: {type: string, unique: true},

ID is used to record a unique schema. Later, it was found that schema itself has an attribute to identify uniqueness, that is, objectid primary key, a special and very important type. Each schema will configure this attribute by default, and the attribute name is_ ID, which can only be overridden unless it is defined by itself
so I delete the ID attribute defined by myself (the database is not cleared), and then an error will be reported every time I add a siteschema. The error message is: mongoerror: e11000 duplicate key error index: airport. Sites. $ID_ 1dup key: {: null})

after searching for the cause of the problem for a long time, it was found that even if the ID attribute of siteschema was deleted in the code, this field still exists in the database. Therefore, if an instance of siteschema is created again, an error with this attribute repeatedly null will be reported

in case of such a problem, you just need to empty the database or delete the corresponding collection (I didn’t try the latter, so I guess it’s OK ^ ^ ^)

Similar Posts: