Mongoose / MongoDB 对路径“_id”执行更新将修改不可变字段“_id”

Cyg*_*nus 3 javascript mongoose mongodb

您好,我正在尝试为我的 SPA 添加更新功能,但似乎遇到了这个问题

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))
})
Run Code Online (Sandbox Code Playgroud)

它捕获了这个错误

Performing an update on the path '_id' would modify the immutable field '_id'
Run Code Online (Sandbox Code Playgroud)

我不确定这里发生了什么,因为据我了解,我并没有尝试更新 _field ,如果我的方法试图自动执行此操作,那么更好的方法是什么?

Jer*_*lle 5

因为您正在传递完整的 Mongoose 模型作为更新。

您正在使用const blog = Blog({ ... }),这将创建一个带有自动 _id 的完整 Mongoose 模型。

该对象作为更新传递。由于它有自己的 _id,因此更新会被拒绝,因为 _id 是一个不可变字段。

解决方案:传递一个简单的对象作为更新,而不是完整的 Mongoose 模型。

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))
})
Run Code Online (Sandbox Code Playgroud)