Ricardo Mota Ricardo Mota - 2 months ago 7
Node.js Question

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

I'm trying to update a value in a MongoDB document. 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.

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.

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.

Answer

Since you're using node.js, you can make use of computed property names, just by wrapping the names in brackets:

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.