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

Node.js与Mongoose中$inc查询动态路径渲染问题求助

Fixing Dynamic $inc Paths in MongoDB with Node.js

Got it, let's sort out this issue you're facing! The problem here boils down to how JavaScript handles object keys when you use variables directly in object literals.

Why Your Current Code Isn't Working

When you write colorPath: -qty in the $inc object, JavaScript treats colorPath as a literal string key—not the value stored in the colorPath variable. So instead of targeting something like colors.2.quantity, MongoDB is looking for a field literally named colorPath, which doesn't exist in your document. That's why the array updates aren't taking effect.

Solution 1: Use ES6 Computed Property Names (Cleanest Approach)

ES6 introduced computed property names, which let you use variables directly as object keys by wrapping them in square brackets. This works perfectly for your dynamic path needs:

// Example values (replace with your actual qty and index)
const qty = 5;
const index = 2;

// Generate dynamic paths
const colorPath = `colors.${index}.quantity`;
const sizePath = `size.${index}.quantity`;

// Build the update query with computed keys
const updateQuery = {
  $inc: {
    quantity: -qty,
    saled: qty,
    [colorPath]: -qty, // Square brackets tell JS to use the variable's value
    [sizePath]: -qty
  }
};

Solution 2: Build the $inc Object Step-by-Step (ES5 Compatible)

If you're working in an environment that doesn't support ES6 features, you can create the $inc object first, then add the dynamic keys using bracket notation:

// Example values
const qty = 5;
const index = 2;

const colorPath = `colors.${index}.quantity`;
const sizePath = `size.${index}.quantity`;

// Initialize base $inc properties
const incObject = {
  quantity: -qty,
  saled: qty
};

// Add dynamic paths using bracket assignment
incObject[colorPath] = -qty;
incObject[sizePath] = -qty;

// Final update query
const updateQuery = { $inc: incObject };

How This Works

Both methods ensure that the dynamic paths (like colors.2.quantity or size.1.quantity, depending on your index value) are properly used as keys in the $inc object. MongoDB will then recognize these paths and update the correct elements in your colors and size arrays, no matter what the index is.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:55:56