1

Please help me. I have o problem like this. I have my query :

$inc: {
    quantity: -qty,
    saled: qty,
    'colors.2.quantity' :  -qty,
    'size.1.quantity' : -qty 
},

The query above work fine. But if i, render path for update color and size like this by Nodejs :

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

Then query like this :

$inc: {
    quantity: -qty,
    saled: qty,
    colorPath :  -qty,
    sizePath : -qty 
},

It does't work. The index of item in colors or size array is not fixed. So, i need to pass like above. How can i do that, please help me... Thanks for your time :'(

Ivan Beldad
  • 2,285
  • 2
  • 21
  • 33
Truong Dang
  • 3,119
  • 1
  • 15
  • 21

1 Answers1

1

Change

$inc: {
    quantity: -qty,
    saled: qty,
    colorPath :  -qty,
    sizePath : -qty 
},

with

$inc: {
    quantity: -qty,
    saled: qty,
    [colorPath] : -qty,
    [sizePath] : -qty 
},

When you are writing colorPath it get interpreted as a string. Using the notation[] will tells the interpretor that you are using a variable.


See here an other stack overflow post about dynamical keys.

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69