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

Node.js中MongoDB嵌套对象访问与更新问题解决

解决MongoDB中动态访问数字键嵌套对象并修改slotCount的问题

我的MongoDB文档结构如下:

{ 
  characterName: character.characterName, 
  0: { slotName: "", slotCount: 0 }, 
  1: { slotName: "", slotCount: 0 }, 
  2: { slotName: "", slotCount: 0 }, 
  3: { slotName: "", slotCount: 0 } 
}

需求是通过API访问任意数字编号的键,修改对应的slotCount值。

最初尝试了这种写法:

db.Inventories.updateOne( 
  { characterName: user.selectedCharacter.CharacterName }, 
  { $set: { [req.query.slotNumber].0.slotCount: req.query.itemCount } } 
);

但VSCode提示语法错误,原因是不允许在方括号包裹的键后直接使用句号。

最终有效的解决方案是:先创建一个拼接好的字符串变量作为键路径:

const key = `${req.query.slotNumber}.slotCount`;

然后在更新操作中通过方括号引用这个变量:

db.Inventories.updateOne( 
  { characterName: user.selectedCharacter.CharacterName }, 
  { $inc: { [key]: -1 } } 
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:11:27