代码之家  ›  专栏  ›  技术社区  ›  K20GH

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

  •  1
  • K20GH  · 技术社区  · 7 年前

    items 其中包含对象:

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

    我试图更新item数组中meta对象下的一个字段。例如项[0]。元描述从hello world到hello bar

    最初我尝试这样做:

      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);
      });
    

    但不幸的是,这似乎将我的整个items数组变成了一个如下所示的对象:

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

    你知道我怎么更新我想要的内容吗?

    1 回复  |  直到 7 年前
        1
  •  16
  •   Doug Stevenson    7 年前

    Firestore无法更新索引数组中的现有元素。中介绍了更新的唯一阵列选项 documentation

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

    推荐文章