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

Mongoose查询嵌套JSON记录并更新数组字段的实现代码怎么写

Mongoose更新嵌套数组字段实现方案

前置准备

首先基于你提供的Schema创建User模型:

const User = mongoose.model('User', userSchema);

方案1:原子更新(推荐)

使用MongoDB位置操作符$直接定位匹配的数组元素,单条语句完成更新,性能高、无并发脏写问题:

// 替换为实际需要匹配的邮箱和计划标识
const targetEmail = "user@test.com";
const targetPlan = "yearly_vip";

const res = await User.updateOne(
  // 匹配条件:同时命中用户邮箱和数组中对应plan的条目
  {
    email: targetEmail,
    "purchasedPlans.plan": targetPlan
  },
  // 更新逻辑:$自动指向匹配到的数组元素
  {
    $set: {
      "purchasedPlans.$.status": "Active"
    }
  }
);

// 可选:判断更新结果
if (res.matchedCount === 0) {
  console.log("未找到对应用户或该用户未购买指定计划");
} else if (res.modifiedCount === 0) {
  console.log("计划状态已为Active,无需重复更新");
}

方案2:先查询后修改

适合更新前需要做额外业务判断的场景:

const targetEmail = "user@test.com";
const targetPlan = "yearly_vip";

// 查询对应用户
const user = await User.findOne({ email: targetEmail });
if (!user) return console.log("用户不存在");

// 查找目标计划条目
const planItem = user.purchasedPlans.find(item => item.plan === targetPlan);
if (!planItem) return console.log("用户未购买该计划");

// 修改后保存
planItem.status = "Active";
await user.save();
console.log("更新成功");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:30:00