Node.js与Mongoose中$inc查询动态路径渲染问题求助
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

