[英]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. 这是为了表明它有效,但是当我使用第一个解决方案时,它会抛出一个错误的
Unexpected token
。
My question is, how can I get the top solution to work as the Object key? 我的问题是,如何让顶级解决方案作为Object键工作?
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 另请参见在JavaScript对象文字中使用变量作为键
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.