Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose / MongoDB Performing an update on the path '_id' would modify the immutable field '_id'

Hi i'm trying to add an update function for my SPA and seem to be running into this issue

blogsRouter.put('/:id', (request, response) => {

const body = request.body

const blog = Blog ({
  title: body.title,
  author: body.author,
  url: body.url,
  likes: body.likes,
  userId: body.userId,
  userName: body.userName
})

Blog.findByIdAndUpdate(request.params.id, blog)
  .then(updatedBlog => {
    response.json(updatedBlog.toJSON())
  })
.catch(error => console.log(error))
})

it catches this error

Performing an update on the path '_id' would modify the immutable field '_id'

I'm not sure what is happening here since to my understanding i'm not trying to update the _field and if my approach is trying to do it automatically what would be a better way to do this?

like image 385
Cygnus Avatar asked Jan 24 '26 15:01

Cygnus


1 Answers

Because you are passing a full Mongoose model as update.

You are using const blog = Blog({ ... }), this creates a full Mongoose model with an automatic _id.

This object is passed as an update. Since it has its own _id, the update is rejected because _id is an immutable field.

Solution : pass a simple object as update, not a full Mongoose model.

blogsRouter.put('/:id', (request, response) => {

const body = request.body

const blog = { // <-- Here
  title: body.title,
  author: body.author,
  url: body.url,
  likes: body.likes,
  userId: body.userId,
  userName: body.userName
}

Blog.findByIdAndUpdate(request.params.id, blog)
  .then(updatedBlog => {
    response.json(updatedBlog.toJSON())
  })
.catch(error => console.log(error))
})
like image 115
Jeremy Thille Avatar answered Jan 26 '26 03:01

Jeremy Thille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!