Mongoose使用findByIdAndUpdate无报错但数据库文档未更新如何解决
问题根因
核心错误出在service层findOneAndUpdate的更新参数写法上:
原代码中第二个参数写为{ userData },属于对象简写语法,等价于{ userData: userData },相当于你试图给文档新增一个名为userData的字段来存储所有更新内容,但你的User Schema中没有定义该字段,Mongoose默认会忽略Schema未声明的字段,因此没有实际更新操作生效,日志中也只会输出查询记录而没有更新记录。
修复方案
去掉service层更新参数里userData外层的大括号,直接传入更新字段即可:
public async updateUser(userId: string, userData: CreateUserDto): Promise<User> { if (isEmpty(userData)) throw new HttpException(400, "You're not userData"); if (userData.email) { const findUser: User = await this.users.findOne({ email: userData.email }); if (findUser && findUser._id != userId) throw new HttpException(409, `You're email ${userData.email} already exists`); } if (userData.password) { const hashedPassword = await bcrypt.hash(userData.password, 10); userData = { ...userData, password: hashedPassword }; } // 仅修改这一行即可,去掉userData外层的大括号 const updateUserById: User = await this.users.findOneAndUpdate({ _id: userId }, userData, { new: true }); if (!updateUserById) throw new HttpException(409, "You're not user"); return updateUserById; }
可选验证项
如果修复后仍存在问题,可检查两项配置:
- 确认Schema中的
email、password字段没有设置immutable: true这类禁止更新的属性 - 如果你使用的是Mongoose 5及更低版本,可在数据库连接配置中添加
useFindAndModify: false,避免方法兼容问题
内容的提问来源于stack exchange,提问作者user7104332
相关产品推荐
相关产品推荐

