Reputation: 33
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?
Upvotes: 3
Views: 4523
Reputation: 26390
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))
})
Upvotes: 5