javascript - Firestore 更新数组字段中的单个项目

标签 javascript arrays firebase object google-cloud-firestore

我在 Firebase Firestore 中有一个类似于以下内容的文档。这里的要点是我有一个名为 items 的数组,其中包含对象:

{
 name: 'Foo',
 items: [
   {
     name: 'Bar',
     meta: {
        image: 'xyz.png',
        description: 'hello world'
     }
   },
   {
     name: 'Rawr',
     meta: {
        image: 'abc.png',
        description: 'hello tom'
     }
   }
 ]
}

我正在尝试更新元对象下项目数组内的字段。例如从 hello world 到 hello bar 的 items[0].meta.description

最初我尝试这样做:

  const key = `items.${this.state.index}.meta.description`
  const property = `hello bar`;

  this.design.update({
    [key]: property
  })
  .then(() => {
    console.log("done")
  })
  .catch(function(error) {
    message.error(error.message);
  });

但这似乎不起作用,因为它删除了我想要修改的项目索引中的所有内容,而只将描述保留在元对象下

我现在正在尝试以下操作,基本上用新数据重写整个元对象

  const key = `items.${this.state.index}.meta`
  const property = e.target.value;
  let meta = this.state.meta;
  meta[e.target.id] = property;

  this.design.update({
    [key]: meta
  })
  .then(() => {
    this.setState({
    [key]: meta
    })
  })
  .catch(function(error) {
    message.error(error.message);
  });

不幸的是,这似乎将我的整个项目数组变成了一个看起来像这样的对象:

{
 name: 'Foo',
 items: {

   0: {
     name: 'Bar',
     meta: {
        image: 'xyz.png',
        description: 'hello world'
     }
   },
   1: {
     name: 'Rawr',
     meta: {
        image: 'abc.png',
        description: 'hello tom'
     }
   }
 }
}

有什么想法可以更新我想要的内容吗?

最佳答案

Firestore 无法更新索引数组中的现有元素。 documentation 中描述了您唯一的更新阵列选项。 - 您可以向数组添加新元素(“arrayUnion”)或删除元素(“arrayRemove”)。

作为替代方案,您可以从文档中读取整个数组,在内存中对其进行修改,然后完全更新修改后的数组字段。

关于javascript - Firestore 更新数组字段中的单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56493659/

相关文章:

javascript - React + Flux, ES6, Babel ActionCreate using json-server and super agent, 数据不响应

javascript - jQuery 从 div 的 CSS 值切换

python - 从字典数组中提取数字数组

javascript - 以递归方式动态向对象添加数据

javascript - 在 PHP 中创建启用和禁用按钮

sql - 如何从postgresql中具有id列表的列中进行选择

c# - 获取数组中最接近的值

javascript - 使用 JavaScript 移动 HTML 表格中的项目

javascript - 如何在 React Native 中拥有多个带有过滤数据的 Flatlist

firebase - 如何在 us-central1 以外的区域使用 httpsCallable for web