14

I am trying to use a variable as the field name in an update statement and it is not working at all, any suggestions?

for example:

COLLECTIONNAME.update(
    { _id: this._id },
    { $set: { VARIABLE1 : VARIABLE2 } }
);

actual code:

 'blur .editable' : function () {
      var target = event.currentTarget.value;
      var field = event.currentTarget.name;
      field = ' " ' + field + ' " ';
      Hostings.update( { _id: this._id },{ $set: { field : target } } );
    }

3 Answers 3

14

You can do it this way:

'blur .editable' : function () {
  var target = event.currentTarget.value;
  var field = event.currentTarget.name;

  var obj = {};
      obj[field] = target;
  Hostings.update( { _id: this._id },{ $set: obj } );
}

Javascrip objects can be accessed two ways:

object.attribute

or

object["attribute"]

if you use the second method you can access it with a variable

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

3 Comments

beautiful! I just had to remove this line: field = ' " ' + field + ' " '; and it worked perfectly. Thanks so much!
Hostings.update( { _id: this._id },{ $set: { [field]: target } } ); Would also work
How does []work internally? Does it enforce mongo to use the key from outside the anonymous function? Why is it not needed for the value ?
5

As per L. Norman's comment, I find using the [] for the field value works instead

collection = "my_collection"
db.getCollection(collection).find({}).forEach(function(doc) {
    var new_field = "new_field";
    var new_value = "new_value";

    db.getCollection(collection).update({_id: doc._id}, 
        {$set: {[new_field] : new_value}}) 
})

1 Comment

This was the simplest solution that worked. Placing the field value in [ ] was the solution to the same issue I was having.
1

for your query
COLLECTIONNAME.update( { _id: this._id },{ $set: { VARIABLE1 : VARIABLE2 } } ); mongodb will take value of VARIABLE2 but it will consider "VARIABLE1" to be a field in the document.

For passing a variable whose value is a field name:

you will have to create a javascript object and use it as follows:

var obj={};
obj[VARIABLE1] = VARIABLE2; //where VARIABLE1 and VARIABLE2 are getting values from elsewhere earlier

If you want to have multiple fields this way, just add it to the same object:

obj[VARIABLE3]= VARIABLE4;

Then do update operation as:

db.collectionname.update( { _id: this._id },{ $set: obj } );

Comments

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.