meteor collection hooks updating element on a position in array

末鹿安然 提交于 2020-01-16 15:46:25

问题


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.


回答1:


Found a solution:

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



回答2:


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.



来源:https://stackoverflow.com/questions/52163399/meteor-collection-hooks-updating-element-on-a-position-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!