Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

javascript - MongoDB Object key with ES6 template string

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...