MongoDB Object key with ES6 template string

2020-02-12 07: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}`: 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?

2条回答
Anthone
2楼-- · 2020-02-12 07:51

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

查看更多
唯我独甜
3楼-- · 2020-02-12 07:53

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); 
查看更多
登录 后发表回答