0

First I create a model as follows

const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

Then I create some users using User.create() and make POST requests from Postman.

I send the following body:

{
  "newData":{
    "name":"abc",
    "email":"abc@email.com",
    "password":"secretPassword"
  }
}

I get an automatically generated "_id" key.

Next I use User.findById() to make a GET request on the _id which works fine.

Next I try User.findByIdAndUpdate() and make a POST request and send the following as body,

{
  "newData":{
    "name":"abc",
    "email":"abc@email.com",
    "password":"newPassword"
  }
}

I get error as follows :

"errmsg": "E11000 duplicate key error collection: userData.users index: email_1 dup key: { email: \"abc@email.com\" }"

the User.findByIdAndUpdate() method is as follows:

User.findByIdAndUpdate(
    req.params.id,
    {
      name:req.body.newData.name,
      email:req.body.newData.email,
      password:req.body.newData.password
    },
    {
      new:true
    },
    (err,data)=>{
      if (err){
        res.json({
          success: false,
          message: err
        })
      } else if (!data){
        res.json({
          success: false,
          message: "Not Found"
        })
      } else {
        res.json({
          success: true,
          data: data
        })
      }
    }
  )
})

What should I do in order to make the code work ?

Sohit Gore
  • 438
  • 1
  • 5
  • 13
  • you have to look in to this https://stackoverflow.com/questions/24430220/e11000-duplicate-key-error-index-in-mongodb-mongoose – turivishal Jul 31 '20 at 06:43
  • @turivishal I get no error when creating new users, the problem persists only on trying to update an existing user. – Sohit Gore Jul 31 '20 at 07:11
  • @turivishal Still doesn't work, i get the same error. – Sohit Gore Jul 31 '20 at 07:33
  • Okay then your problem's solution in above link post that i have shared read all answers properly, the error is related to index on email field, you can try with droping database or index. – turivishal Jul 31 '20 at 07:41

0 Answers0