You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Mongoose的findOneAndUpdate一次性获取MongoDB更新后文档

用Mongoose的findOneAndUpdate一次完成更新并返回最新文档

你完全不需要发起两次数据库请求,Mongoose的findOneAndUpdate方法支持通过配置选项直接返回更新后的文档,核心是设置new: true参数。

修改后的代码如下:

module.exports.addcontact = async (req, res) => {
  // 注意:原代码里的req.bode是req.body的笔误,建议修正
  const updatedUser = await UserModel.findOneAndUpdate(
    { email: email },
    { $set: { number : req.body.number } },
    { 
      new: true, // 关键配置:返回更新后的文档
      runValidators: true // 可选:如果需要触发Schema的验证规则,加上这个
    }
  );

  if (!updatedUser) {
    // 可选:处理用户不存在的情况
    return res.send({ stat: false, message: "用户不存在" });
  }

  res.send({ stat: true, decode, wallets: updatedUser.Wallets });
}

关键参数说明

  • new: true:默认情况下findOneAndUpdate返回更新前的文档,设置该参数后,方法会直接返回更新后的最新文档。
  • runValidators: true:如果你的UserSchema对number字段有验证规则(比如格式、长度限制),加上这个参数会在更新时触发验证,避免存入不符合规则的数据。

内容的提问来源于stack exchange,提问作者Geekyvinayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:04:54