Using Variables in MongoDB Update Instructions

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

eg:

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

valid code:

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

You can do it as follows:

 '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 in two ways:

 object.attribute 

or

 object["attribute"] 

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

+12
source

for your request
COLLECTIONNAME.update( { _id: this._id },{ $set: { VARIABLE1 : VARIABLE2 } } ); mongodb will take the value VARIABLE2, but it will treat "VARIABLE1" as a field in the document.

To pass a variable whose value is the name of the field:

you will need to create a javascript object and use it like this:

 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 them to the same object:

 obj[VARIABLE3]= VARIABLE4; 

Then perform the update operation as:

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

Source: https://habr.com/ru/post/952714/


All Articles