使用 Meteor,我尝试执行如下更新:
Items.update(Session.get('selectedItem'), {'$set': {'directions.0.name': area.value}})
但是我正在努力解决如何动态设置方向数组索引的问题,如下所示:
var index = //a value determined dynamically
Items.update(Session.get('selectedItem'), {'$set': {'directions[index]name': area.value}})
这不起作用,因为 [index] 被包裹在字符串中。我还尝试形成一个自定义字符串,如下所示:
var string = 'directions.'+itemIndex+'.name'
Items.update(Session.get('selectedItem'), {'$set': {string: area.value}})
但这行不通。知道如何做到这一点吗?
最佳答案
您需要以编程方式构建您的 $set
对象:
var setModifier = { $set: {} };
setModifier.$set['directions.' + index + '.name'] = area.value;
Items.update(Session.get('selectedItem'), setModifier);
更新
如果您的 JavaScript 环境支持computed property names (例如node.js 4+),您可以一步完成此操作:
Items.update(Session.get('selectedItem'), { $set: {
['directions.' + index + '.name']: area.value
}});
关于javascript - 在 mongodb 更新中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24779305/