如何在没有 eval 的情况下在 JavaScript 中使用动态变量名来更新 MongoDB? [英] How to use a dynamic variable-name in JavaScript without eval for a MongoDB update?

查看:15
本文介绍了如何在没有 eval 的情况下在 JavaScript 中使用动态变量名来更新 MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Meteor 应用程序中,我有一个事件应该更新数据库数据用于更改表单上的字段.

In a Meteor application I have an event that should update the database data for changed fields on a form.

所以事件处理程序看起来像这样:

So the event handler looks like this:

Template.someTemplate.events({'change #someForm' : function(){
    eval("someCollection.update(Session.get(\"currentId\"), {$set: {" + event.target.name + ":event.target.value}});");
}})

这很好用,当我使用 eval 时.但我怀疑像这样使用 eval 是否被认为是最佳实践,或者是吗?

This works fine, when I use eval. But I doubt it is considered a best practice to use eval like this, or is it?

我必须如何编写 MongoDB 更新代码才能使类似以下工作?

How would I have to write the MongoDB-update code, to make something like the following work?

  Template.someTemplate.events({'change #someForm' : function(){
    var variableName = event.target.name;
    someColletion.update(Session.get("currentId"), {$set: {variableName:event.target.value}});
  }})

或者解决这个问题的正确方法是什么?(上面的代码不起作用,对于 MongoDB 更新指令,variableName 没有被计算,所以variableName"被传递而不是它的设置值.

Or what is the right way, to approach this? (The code above does not work, as for the MongoDB update instruction the variableName is not evaluated, so "variableName" is passed instead of its set value.

请注意,我想将其用于原型设计,而不是真正的应用程序.所以安全实际上并不是一个真正的问题.(我是 UX 专家,不是软件工程师.)

Note that I want to use this for prototyping, not actually a real application. So security is actually not really an issue. (I am a UX guy, not a software engineer.)

推荐答案

您需要使用索引器表示法创建对象:

You need to create the object using indexer notation:

var param = { $set: {} };
param.$set[event.target.name] = event.target.value;
someCollection.update(Session.get("currentId"), param);

这篇关于如何在没有 eval 的情况下在 JavaScript 中使用动态变量名来更新 MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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