2

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.

3
  • What JavaScript run time environment are you using? Commented Oct 7, 2016 at 11:18
  • I'm using Node.js if that is what you wanted to know. Commented Oct 7, 2016 at 11:19
  • 2
    You are not dealing with JSON here. JSON always is a string, and nothing else (the contents of that string looks a like Javascript, but it isn't). What you are dealing with here are simply native objects, i.e. object literals. Commented Oct 7, 2016 at 11:23

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect. Thank you. So that is the equivalent of using {{ }} in angular?
@RicardoMota No idea - I'm not an angular guy :)
Fair enough :) I'll accept your answer as soon as the system allows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.