glasses
glasses

Reputation: 763

Using variables in MongoDB update statement

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 } } );
    }

Upvotes: 14

Views: 20932

Answers (3)

Yi Xiang Chong
Yi Xiang Chong

Reputation: 764

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}}) 
})

Upvotes: 5

learner_19
learner_19

Reputation: 4101

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 } );

Upvotes: 1

Jonathan Crowe
Jonathan Crowe

Reputation: 5803

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

Upvotes: 14

Related Questions