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

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

问题描述

使用 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 更新中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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