使用 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 })
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于