mongoose 更新数据发生冲突 MongoError: Performing an update on the path '_id' would modify the immutable field '_id'

本贴最后更新于 1577 天前,其中的信息可能已经斗转星移

使用 Node.js 库 mongoose 操作 MongoDB 遇到的问题

报错日志

MongoError: Performing an update on the path '_id' would modify the immutable field '_id'  
 at Connection.<anonymous> (D:\Joey\dev\LocalLibrary\node_modules\mongodb\lib\core\connection\pool.js:460:61)  
 at Connection.emit (events.js:198:13)  
 at processMessage (D:\Joey\dev\LocalLibrary\node_modules\mongodb\lib\core\connection\connection.js:368:10)  
 at Socket.<anonymous> (D:\Joey\dev\vscode\LocalLibrary\node_modules\mongodb\lib\core\connection\connection.js:537:15)  
 at Socket.emit (events.js:198:13)  
 at addChunk (_stream_readable.js:288:12)  
 at readableAddChunk (_stream_readable.js:269:11)  
 at Socket.Readable.push (_stream_readable.js:224:10)  
 at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)  

依赖版本

"mongoose": "^5.7.13"

调试代码

   const book = new Book({
      title: req.body.title,
      author: req.body.author,
      summary: req.body.summary,
      isbn: req.body.isbn,
      genre: (typeof req.body.genre === 'undefined') ? [] : req.body.genre
    })

    console.log('----->', book)

    console.log('id------->', req.params.id)

    Book.findByIdAndUpdate(req.params.id, book, {}, function (err, thebook) {
      if (err) { return next(err) }
      res.redirect(thebook.url)
    })

输出

book-----> { genre: [ 5de4ef45e8e406006434529c, 5de4ef45e8e406006434529e ],
  _id: 5de6527468794d2c9ccabadf,
  title: '朝花夕拾',
  author: 5de4ef45e8e40600643452a1,
  summary:
   '本书是一本具有鲜明的个性色彩的散文集。适性任隋、洒脱不羁,想说就说,想骂就骂,心中的种种爱憎悲
欢,任其在笔下自然流泻。抒情、叙事和议论融为一体,优美和谐,朴实感人。',
  isbn: '9787514370829' }
id-------> 5de4ef45e8e40600643452a7                                                    
  

在创建 Book 之后就有了 _id 字段,不知是怎么来的,与更新目标的 _id 字段不一致,而该字段是不可修改的,因此操作失败

解决办法:

创建 Book 的时候把要更新的文档的 _id 塞进去

    const book = new Book({
      _id: req.params.id,
      title: req.body.title,
      author: req.body.author,
      summary: req.body.summary,
      isbn: req.body.isbn,
      genre: (typeof req.body.genre === 'undefined') ? [] : req.body.genre
    })
  • Node.js

    Node.js 是一个基于 Chrome JavaScript 运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞 I/O 模型而得以轻量和高效。

    138 引用 • 268 回帖 • 218 关注
  • MongoDB

    MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是一个基于分布式文件存储的数据库,由 C++ 语言编写。旨在为应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。

    90 引用 • 59 回帖 • 4 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...