Vallabha
Vallabha

Reputation: 1621

update document using a unique filed with findOneAndUpdate is thorwing exception

I am new to node.js and mean.

I have nearly 20 fields to update in a document.

var UserSchema = mongoose.model('UserSchema');

I am passing these 20 fields in the request body and updating the UserSchema model object.

var newUser =new  UserSchema(req.body);

Actually i am not passing _id from my request body but when i saw my newUser._id it is filled up with some id, so it resulting in an error called

exception: After applying the update to the document {_id: ObjectId('560e506ad4369d2a02a6ad6d') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('560e65f395857e210313d3a7')



  UserSchema.findOneAndUpdate({ userName: newUser.userName }, newUser, { new: true }, function (err, newuser) {
      if (err) {
        console.log(err);
        return res.status(400).json({ message: err });
      }
      return res.status(200).json({ result: newUser });
    });

Upvotes: 0

Views: 1224

Answers (1)

Gaurav Gandhi
Gaurav Gandhi

Reputation: 3201

Because you are creating new record set by following statement,

 var newUser =new  UserSchema(req.body);

Above statement will match all provided fields by req.body with registered schema for UserSchema Model and will generate new ObjectId for it. So newUser variable have _id field and when you try update existing record with newUser, it causes error as you are trying to change immutable _id field.

Instead you can re-write whole as following,

var UserSchema = mongoose.model('UserSchema');
var newUser = req.body;

UserSchema.findOneAndUpdate({ userName: newUser.userName }, newUser, { new: true }, function (err, newuser) {
      if (err) {
        console.log(err);
        return res.status(400).json({ message: err });
      }
      return res.status(200).json({ result: newUser });
    });

And if provided record does not exists then findOneAndUpdate will insert new as you provided new: true flag.

Upvotes: 1

Related Questions