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

MongoDB updateOne+upsert逻辑异常:如何修复汇率数据更新问题?

修复Mongoose汇率集合Upsert时的更新错误

问题原因

当执行upsert创建新文档时,exchange字段尚未存在,此时$exchange.year会返回missing,导致$in操作符因第二个参数不是合法数组而抛出错误。

修复方案

核心是先处理exchange字段不存在的场景,用$ifNull将不存在的exchange转换为空数组,确保$in操作始终能拿到合法的数组参数,同时覆盖三种更新逻辑:

  • 文档不存在:upsert创建新文档,exchange初始化为包含当前{year, rate}的数组
  • 文档存在但无对应年份:将{year, rate}追加到exchange数组
  • 文档存在且有对应年份:更新对应年份的汇率值

修复后的完整代码

const response = await Currencies.updateOne(
  { source, convert },
  [{
    $set: {
      exchange: {
        $cond: [
          // 先处理exchange不存在的情况,转为空数组后再检查年份是否存在
          { $in: [year, { $ifNull: ["$exchange.year", []] }] },
          // 场景3:存在对应年份,更新汇率
          {
            $map: {
              input: "$exchange",
              in: {
                $cond: [
                  { $eq: ["$$this.year", year] },
                  { year: "$$this.year", rate: rate },
                  "$$this"
                ]
              }
            }
          },
          // 场景1和2:不存在对应年份,追加新汇率项(exchange不存在时自动转为空数组)
          { $concatArrays: [{ $ifNull: ["$exchange", []] }, [{ year: year, rate: rate }]] }
        ]
      }
    }
  }],
  { upsert: true }
)

代码说明

  • { $ifNull: ["$exchange.year", []] }:当exchange字段不存在时,返回空数组,避免$in操作因参数非法报错
  • { $concatArrays: [{ $ifNull: ["$exchange", []] }, [{ year: year, rate: rate }]] }:处理文档不存在($exchange为null,转为空数组)或存在但无对应年份的情况,将新汇率项追加到数组中
  • $map逻辑:遍历现有exchange数组,匹配到目标年份时更新汇率,其余项保持原结构不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:17:05