Firestore 更新数组字段中的单个项目 [英] Firestore Update single item in an array field

查看:27
本文介绍了Firestore 更新数组字段中的单个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Firebase Firestore 中有一个类似于下面的文档.这里的要点是我有一个名为 items 的数组,里面有对象:

I have a document in Firebase Firestore that is something like the below. The main point here is that I have an array called items with objects inside it:

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

我正在尝试更新元对象下的 item 数组中的一个字段.例如 items[0].meta.description 从 hello world 到 hello bar

I am trying to update a field inside the item array, under the meta object. For example items[0].meta.description from hello world to 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);
  });

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

This didn't appear to work though, as it removed everything in the item index I wanted to modify, and just kept the description under the meta object

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

I am now trying the following which basically rewrites the whole meta object with the new data

  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 数组变成了一个看起来像这样的对象:

Unfortunately though, this seems to turn my whole items array into an object that looks something like:

{
 name: 'Foo',
 items: {

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

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

Any ideas how I can just update the content I want to?

推荐答案

Firestore 无法更新索引数组中的现有元素.文档中描述了您唯一的更新数组选项- 您可以向数组中添加一个新元素(arrayUnion")或删除一个元素(arrayRemove").

Firestore doesn't have the ability to update an existing element in an indexed array. Your only array options for updates are described in the documentation - you can add a new element to the array ("arrayUnion") or remove an element ("arrayRemove").

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

As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely.

这篇关于Firestore 更新数组字段中的单个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆