[英]Can't update a mongo value with a dynamic array id from a meteor form
I've got a meteor event in which I'm trying to update one value in a number of sub documents from an event handler. 我有一个流星事件,其中我试图从事件处理程序中更新多个子文档中的一个值。
The string I'm putting together is order.0.number, order.1.number etc.. and I can see the correct strings being generated in the debugger. 我放在一起的字符串是order.0.number,order.1.number等。我可以看到调试器中生成了正确的字符串。 I can also manually update the field in the console, but the code stubbonly refuses to update the numbers.
我也可以在控制台中手动更新该字段,但是该代码严格拒绝更新数字。
The event code is 事件代码是
'click #closeEdit': function(evt,tmpl) {
evt.preventDefault();
Session.set('showEditEvent',false);
Session.set('lastMod', new Date());
Requests.update({_id:Session.get('editingReqEvent')}, {$set: {locked_by: null}});
var request = Requests.findOne({_id:Session.get('editingReqEvent')});
for (i=1; i <= request.order.length; i++) {
var val=tmpl.find('#'+i).value;
if(!val) {// its null
val = 0
}
var toSet = "order."+(i-1)+".number";
debugger;
Requests.update({_id:Session.get('editingReqEvent')}, {$set: {toSet: parseInt(val)}});
}
},
Any ideas how I should be doing this (obviously what I have here isn't the way to do it). 关于如何执行此操作的任何想法(显然,我在这里所没有的方法)。
Thanks. 谢谢。
{toSet: parseInt(val)}
In this code toSet
won't evaluate to order.x.number
as it is a key. 在此代码中,
toSet
不会求值为order.x.number
因为它是键。 The update query will try to set the value of the toSet
property in document. 更新查询将尝试在文档中设置
toSet
属性的值。 You can get around this issue with a code like this: 您可以使用以下代码解决此问题:
var toSet = {};
var toSet["order."+(i-1)+".number"] = parseInt(val);
Requests.update({_id:Session.get('editingReqEvent')}, {$set: toSet});
{toSet: parseInt(val)}
will create an object with the key toSet
. {toSet: parseInt(val)}
将创建一个具有toSet
键的对象。 Not what you want, right? 不是您想要的,对不对? You need to do something like:
您需要执行以下操作:
var toSet = "order."+(i-1)+".number"
var updates = {}
updates[toSet] = parseInt(val)
Requests.update(Session.get('editingReqEvent'), {$set: updates})
PS, in your code, create i
as a local variable instead of a global variable (guessing you're not using it as a global variable). PS,在您的代码中,将
i
创建为局部变量而不是全局变量(猜测您没有将其用作全局变量)。 DS DS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.