13

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 } } );
    }
Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
glasses
  • 743
  • 2
  • 8
  • 24

3 Answers3

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

Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28
  • beautiful! I just had to remove this line: field = ' " ' + field + ' " '; and it worked perfectly. Thanks so much! – glasses Aug 29 '13 at 06:48
  • 3
    `Hostings.update( { _id: this._id },{ $set: { [field]: target } } );` Would also work – L. Norman Dec 10 '18 at 21:57
  • 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` ? – Timo Apr 15 '22 at 08:59
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}}) 
})
Yi Xiang Chong
  • 744
  • 11
  • 9
  • This was the simplest solution that worked. Placing the field value in [ ] was the solution to the same issue I was having. – timv Sep 21 '21 at 23:52
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 } );
learner_19
  • 3,851
  • 1
  • 19
  • 8