简体   繁体   English

流星收集挂钩更新元素在数组中的位置上

[英]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. customFields数组位于卡内,包含由id和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? 我必须添加到Modifyer。$ set中以更新此数组中的元素的内容是什么?

Alternate Solution: i have the id of the element in the array if the update can be done on value by using the id. 替代解决方案:如果可以通过使用ID对值进行更新,则我具有数组中元素的ID。

找到一个解决方案:

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

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. 我假设在同一钩子中两次调用super.update()是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM