简体   繁体   English

Javascript:如何通过在字符串中指定字段来创建对象?

[英]Javascript: How can I create an object by specifying the fields in strings?

I'm trying to update a value in a MongoDB document. 我正在尝试更新MongoDB文档中的值。 The document has many fields but I only want to specify a few of them depending on the fields I've changed in the UI. 该文档有许多字段,但是我只想根据我在UI中更改的字段指定其中的一些字段。

var monthField='calendar.m'+month+'.result';
var triField='calendar.t'+trimester+'.result';
var yearField="calendar.year.result";

Objective.update({_id:{$in:objective.parents}},{
    $inc:
    {
        yearField:transaction.value,
        monthField:transaction.value,
        triField:transaction.value
    }},
    {multi:true, upsert:true}
  )

Unfortunately the above code does not "eval" the yearField , monthField and triField to their string values and instead is trying to update as if those fields exist in the document. 不幸的是,上面的代码不“EVAL”的yearFieldmonthFieldtriField他们的字符串值,而是试图更新仿佛文档中存在的这些领域。

I know I can just find the documents, alter the values, and save them all one by one but is there a way to do what I'm trying to do? 我知道我可以找到文档,更改值并逐个保存它们,但是有什么方法可以做我想做的事情? It's just so much better doing it in one update line. 在一条更新行中这样做要好得多。

Since you're using node.js, you can make use of computed property names , just by wrapping the names in brackets: 由于您使用的是node.js,因此只需将名称包装在方括号中,就可以利用计算的属性名称

var monthField='calendar.m'+month+'.result';
var triField='calendar.t'+trimester+'.result';
var yearField="calendar.year.result";

Objective.update({_id:{$in:objective.parents}},{
    $inc:
    {
        [yearField]:transaction.value,
        [monthField]:transaction.value,
        [triField]:transaction.value
    }},
    {multi:true, upsert:true}
)

This syntax was added to the spec in ES2015, and while not ubiquitous yet, it is supported in node.js. 此语法已在ES2015中添加到规范中,尽管尚不普及,但在node.js中受支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM