【问题标题】:using a variable in mongodb update在 mongodb 更新中使用变量
【发布时间】:2012-09-05 18:41:38
【问题描述】:

使用 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}})

但这不起作用。关于如何做到这一点的任何想法?

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    您需要以编程方式构建您的 $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
    }});
    

    【讨论】:

    • 谢谢..这对某些人来说可能看起来很简单,但我只是在学习 mongodb。
    猜你喜欢
    • 2013-09-01
    • 1970-01-01
    • 2016-06-09
    • 2011-05-25
    • 1970-01-01
    • 2014-10-06
    • 2016-05-16
    相关资源
    最近更新 更多