[SOLVED] Dynamically setting a document field in meteor

I am trying to update a field in a document in my collection by dynamically addressing that field. The reason being that I do not wish to update the whole object. But when I do this, another field is created with the same field name as the one I am trying to update. How is this? And is there any way around this problem? I have tried a lot of suggested solutions, but none of which I get a desired result.

Let us say I have a collection document like:

{ _id: "randomid",
  status: 0,
  category: 1
}

And want to update category field. My code adds another category field, resulting in:

{ _id: "randomid",
  status: 0,
  category: 1,
  category: 1
}
Template.listEditObjects.events({
...
Meteor.call('object.update.byfield', object, fieldName, fieldValue, function(error, result) {
  if(error) {
    console.log('Error: ' + error);
  }
});
});

/lib/collections.js

...
Meteor.methods({
  'object.update.byfield'(object, fieldName, fieldValue) {
    Objects.update(
      { _id: id },
      {$set: {
        [fieldName]: fieldValue
      }
    });
  }
});

I’ve just tried this myself and it works correctly. Are you sure there are no “invisible” characters in your fieldName? If I set fieldName = 'category ' it adds another field (with the trailing space).

1 Like

As usual, you are correct. Turned out I needed to trim the fieldName before sending it. Thanks again.

1 Like