6

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}`: item}}); 

This exact string works just fine if I do it like this:

db.collection('connect').update({_id: id}, {$push:  { "list.0.arr": item}}); 

This is to show that it works, but It's throwing an error Unexpected token when I use the first solution.

My question is, how can I get the top solution to work as the Object key?

Ajax jQuery
  • 357
  • 1
  • 5
  • 19

2 Answers2

6

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

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • This does not work. It gives: `SyntaxError: Unexpected token [`. I suspect mongo doesn't support this syntax. (Using version 2.6.11) – hackel Dec 08 '16 at 04:01
  • 1
    @hackel: That has nothing to do with MongoDB, rather with the Node version you are using. See http://node.green for which features are supported in each version. – Felix Kling Dec 08 '16 at 04:03
2

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); 
chridam
  • 100,957
  • 23
  • 236
  • 235
  • Thanks a lot, this worked for me after I was almost gave up , var Now = new Date(); var currMonth = Now.getMonth(); var currYear = Now.getFullYear(); console.log(currYear, currMonth); var query = {shareId: share}, inc = { "$inc": {} }; inc["$inc"][`interactions.views.${currYear}.${currMonth}`] = 1 ; ShareStat.findOneAndUpdate(query, inc); – Abdullah Alkurdi Dec 28 '18 at 16:00