Gobliins
Gobliins

Reputation: 4026

meteor collection hooks updating element on a position in array

i have this object:

card: { customFields [ { id, value }, {id , value } ... ] }

A customFields array is inside cards, which contans elements consisting of an id and a value.

Now i want to update a certain element inside of the array, which can be done by doing something like this:

  modifier.$set.customFields.0.value = x

but i have the number of the index only in a variable, so i tried:

const index = getTargetIndex();
modifier.$set.customFields[index].value = x

but it didn't work...

What do i have to add to the modifier.$set to update an element in this array?

Alternate Solution: i have the id of the element in the array if the update can be done on value by using the id.

Upvotes: 0

Views: 58

Answers (2)

Gobliins
Gobliins

Reputation: 4026

Found a solution:

modifier.$set[`customFields.${  index  }.value`]

Upvotes: 1

rooch84
rooch84

Reputation: 654

It looks like you'll need to do it using a second update:

update(selector, modifier, options, callback) {
  let i = 1;
  let val = 20;

  // The field in the array you want to modify
  let _modifier = {$set: {"customFields.$.value": val}}; 

  // The selector for main element and the array element
  let _selector = Object.assign(selector, {"customFields.id": i}); 

  // Update the array
  super.update(_selector, _modifier);

  // Continue with the actual update
  return super.update(selector, modifier, options, callback);
}

I'm assuming it's safe to call super.update() twice in the same hook.

Upvotes: 0

Related Questions