0

In the code below:

DbModels.prototype.updateById = function(_collection, id, field, value, callback) {
    this.getCollection(_collection, function(error, sel_collection) {
      if( error ) callback(error)
      else {
        sel_collection.update({_id: ObjectID.createFromHexString(id)}, {$set: {$[field].value:value}}, function(error, updated) {
          if( error ) callback(error)
          else callback(null, updated);
        });
      }
    });
};

I would like to use the value of the variable field as the name of the variable in $set. I tried using the following code $[field].value (as you can see in the code above), which doesn't work. Any suggestions how to solve this?

Thanks!

2
  • 3
    The answer is simple: Do not create messy code where hacks like dynamic variable names are necessary. Commented Mar 23, 2012 at 8:10
  • What exactly is messy about this approach? What I intend to do is pass the attribute that needs to be updated and then (dynamically) update only the changed attribute. Commented Mar 23, 2012 at 8:19

1 Answer 1

6

There's not such syntax in javascript as php ${$var_name};

One can use this[var_name] or window[var_name] (for global vars in browsers), but there's no way to get local variable in current scope except eval, which is definitely considered bad.

Consider using a hash (object) for variable "scoping/namespacing".

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

2 Comments

With the last part do you mean something like: var parameters = {}; parameters[firstVariableName] = field; sel_collection.update({_id: ObjectID.createFromHexString(id)}, {$set: {parameters[firstVariableName]:value}},................
Yes, except one can't write object literals this way. And it could be actually done a bit simpler: var setParameters = {}; setParameters[parameters[firstVariableName]] = value; sel_collection.update({_id: ObjectID.createFromHexString(id)}, {$set: setParameters}

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.