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 ?