在mongodb update中使用变量 [英] using a variable in mongodb update

查看:464
本文介绍了在mongodb update中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Meteor,我正在尝试执行如下更新:

Using Meteor, I'm trying to perform an update like the following:

Items.update(Session.get('selectedItem'), {'$set': {'directions.0.name': area.value}})

但是我正在努力设置如何动态设置方向的数组索引,如下所示:

But I'm struggling with how to set the array index of directions dynamically, with something like this:

var index = //a value determined dynamically
Items.update(Session.get('selectedItem'), {'$set': {'directions[index]name': area.value}})

这不起作用,因为[index]包装在一个字符串中。我还试图形成一个自定义字符串,如下所示:

This doesn't work because [index] is wrapped in a string. I also tried to form a custom string, like this:

var string = 'directions.'+itemIndex+'.name'
Items.update(Session.get('selectedItem'), {'$set': {string: area.value}})

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

But that doesn't work. Any idea on how to do this?

推荐答案

你需要建立你的 $ set 以编程方式对象:

You need to build up your $set object programmatically:

var setModifier = { $set: {} };
setModifier.$set['directions.' + index + '.name'] = area.value;
Items.update(Session.get('selectedItem'), setModifier);

更新

如果您的JavaScript环境支持计算属性名称(例如node.js 4+),您可以一步完成:

If your JavaScript environment supports computed property names (e.g. node.js 4+), you can do this in one step:

Items.update(Session.get('selectedItem'), { $set: {
    ['directions.' + index + '.name']: area.value
}});

这篇关于在mongodb update中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆