MongoDB Object key with ES6 template string

后端 未结 2 557
名媛妹妹
名媛妹妹 2020-12-19 10:16

I\'m trying to update an array in my collection with this:

 var str = \"list.0.arr\";
    db.collection(\'connect\').update({_id: id}, {$push:  { `${str}`: i         


        
相关标签:
2条回答
  • 2020-12-19 10:59

    Template literals cannot be used as key in an object literal. Use a computed property instead:

    db.collection('connect').update({_id: id}, {$push: {[str]: item}}); 
    //                                                  ^^^^^
    

    See also Using a variable for a key in a JavaScript object literal

    0 讨论(0)
  • 2020-12-19 11:02

    Create the update document with the string as key prior to using it in the update:

    var str = "list.0.arr",
        query = { "_id": id },
        update = { "$push": {} };
    update["$push"][str] = item;
    db.collection('connect').update(query, update); 
    
    0 讨论(0)
提交回复
热议问题