簡體   English   中英

Firestore 更新數組字段中的單個項目

[英]Firestore Update single item in an array field

我在 Firebase Firestore 中有一份文檔,內容如下所示。 這里的要點是我有一個名為items的數組,其中包含對象:

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

我正在嘗試更新項目數組中的字段,在元 object 下。例如 items[0].meta.description 從 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);
  });

但這似乎沒有用,因為它刪除了我想修改的項目索引中的所有內容,並且只是將描述保留在元 object 下

我現在正在嘗試以下基本上用新數據重寫整個元 object

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

不幸的是,這似乎將我的整個項目數組變成了一個 object,看起來像這樣:

{
 name: 'Foo',
 items: {

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

有什么想法可以更新我想要的內容嗎?

Firestore 無法更新索引數組中的現有元素。 文檔中描述了您唯一的更新數組選項 - 您可以向數組添加新元素(“arrayUnion”)或刪除元素(“arrayRemove”)。

作為替代方案,您可以從文檔中讀取整個數組,在內存中對其進行修改,然后完全更新修改后的數組字段。

您可以為該特定數組創建一個單獨的集合,就像之前這張圖片中的這個一樣,我有不同的名稱字段(沒有集合),email 和頁面,在此,我想更改特定頁面內的數據大批。 為此,我制作了一個不同的頁面集合,每個頁面的單獨文檔都具有標題描述和可以改變的內容的值。 為頁面數組創建的新集合

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM