variable with mongodb dotnotation

后端 未结 2 1158
清酒与你
清酒与你 2021-01-05 01:23

I want to increase a field inside an object object inside a mongodb document by 1.

  var stuffID = 5
  collection.update({
    \"id\": id,
  },
  {
    \'$in         


        
相关标签:
2条回答
  • 2021-01-05 01:35

    Put the variable where it says stuffID.

    'stuff.' + varname: 1
    
    0 讨论(0)
  • 2021-01-05 01:42

    You need to create your variably-keyed object separately, because JS before ES2015 doesn't permit anything other than constant strings in object literal syntax:

    var stuffID = 5
    var stuff = {};                 // create an empty object
    stuff['stuff.' + stuffID] = 1;  // and then populate the variable key
    
    collection.update({
        "id": id,
    }, {
        "$inc": stuff               // pass the object from above here
    }, ...);
    

    EDIT in ES2015, it's now possible to use an expression as a key in an object literal, using [expr]: value syntax, and in this case also using ES2015 backtick string interpolation:

    var stuffID = 5;
    collection.update({
        "id": id,
    }, {
        "$inc": {
            [`stuff.${stuffID}`]: 1
        }
    }, ...);
    

    The code above works in Node.js v4+

    0 讨论(0)
提交回复
热议问题