Is a variable for a field name allowed during update?


#1

I have been trying to update a collection i have.Problem is,i dont know the field name so am relyin on some logic to come up with the field name.

For instance

  Er.update({ _id: "BCwrQEdiTr9GMmKWW" }, {$set: {
		  "x" : y
			 }
 });

where x is the field name. Is this allowed in meteor?.


#2

Meteor doesn’t have any specific syntax - it’s just javascript.

In JS, {"x": y} is an object literal and is more or less the same as {x: y}, except that “x” is now a string (which allows you to do stuff like {"user.name": y})

With ES6 (the latest version of JS) we can now use ‘computed property names’ like this:

let x = 'foo';
let y = 'bar';

// {'foo' : bar'}
let z = {
  [x]: y // [you can put expressions in here]
};

Prior to ES6, you would probably do something like this:

let updateObj = {};

updateObj[x] = y;

Er.update({_id: 'etc...'}, {$set: updateObj});

For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer