E11000 duplicate key error index in mongodb mongoose

前端 未结 25 1984
自闭症患者
自闭症患者 2020-11-22 05:49

Following is my user schema in user.js model -

var userSchema = new mongoose.Schema({
    local: {
        name: { type: String },
         


        
25条回答
  •  孤城傲影
    2020-11-22 06:30

    Well basically this error is saying, that you had a unique index on a particular field for example: "email_address", so mongodb expects unique email address value for each document in the collection.

    So let's say, earlier in your schema the unique index was not defined, and then you signed up 2 users with the same email address or with no email address (null value).

    Later, you saw that there was a mistake. so you try to correct it by adding a unique index to the schema. But your collection already has duplicates, so the error message says that you can't insert a duplicate value again.

    You essentially have three options:

    1. Drop the collection

      db.users.drop();

    2. Find the document which has that value and delete it. Let's say the value was null, you can delete it using:

      db.users.remove({ email_address: null });

    3. Drop the Unique index:

      db.users.dropIndex(indexName)

    I Hope this helped :)

提交回复
热议问题