Mongoose中出现.save is not a function错误:Mongo记录更新失败
问题原因
你调用.save()报错是因为用了.lean()方法——这个方法会把Mongoose查询返回的文档对象转换成普通的JavaScript对象,普通JS对象没有Mongoose提供的.save()方法,自然会报错。
修复方案
这里给你三种可行的修复方式,按需选择:
方案1:移除.lean(),直接操作Mongoose文档
去掉.lean()后,findOne返回的是Mongoose文档实例,自带.save()方法,修改字段后直接保存即可:
async function updateReview (req, res) { const review = { ...req.body } try { const existingReview = await Review.findOne({ userId: review.userId, launchId: review.launchId }) // 移除.lean() if (!existingReview) { return res.status(404).send('评论不存在') } // 修改字段 existingReview.content = review.content existingReview.displayName = review.displayName existingReview.rating = review.rating await existingReview.save() // 现在可以正常调用save() return res.status(200).send(existingReview) } catch (err) { res.status(500).send(err.message) } }
注意:这种方式会自动触发Schema定义的验证规则,适合需要验证更新内容的场景。
方案2:用findOneAndUpdate直接在数据库更新(更高效)
不需要先查询再保存,一步到位完成查询+更新,性能更好:
async function updateReview (req, res) { const { userId, launchId, content, displayName, rating } = req.body try { const updatedReview = await Review.findOneAndUpdate( { userId, launchId }, // 查询条件 { $set: { content, displayName, rating } }, // 要更新的字段 { new: true, runValidators: true } // new: true返回更新后的文档;runValidators: true触发Schema验证 ) if (!updatedReview) { return res.status(404).send('评论不存在') } return res.status(200).send(updatedReview) } catch (err) { res.status(500).send(err.message) } }
方案3:用updateOne执行更新(无需返回更新后的数据)
如果只需要确认更新成功,不需要返回更新后的文档,用updateOne更轻量:
async function updateReview (req, res) { const { userId, launchId, content, displayName, rating } = req.body try { const result = await Review.updateOne( { userId, launchId }, { $set: { content, displayName, rating } } ) if (result.nModified === 0) { return res.status(404).send('评论不存在或未修改') } return res.status(200).send('评论更新成功') } catch (err) { res.status(500).send(err.message) } }
内容的提问来源于stack exchange,提问作者mcool
相关产品推荐
相关产品推荐

