首頁 > web前端 > js教程 > 主體

如何更新 Firestore 中陣列欄位中的單一項目?

Linda Hamilton
發布: 2024-11-15 10:02:03
原創
433 人瀏覽過

How to Update a Single Item in an Array Field in Firestore?

Updating Single Item in an Array Field in Firestore

The FirebaseFirestore documentation describes ways to interact with array fields, including adding or removing elements. However, it lacks a method for directly updating an item inside the array.

For a document like:

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

To modify a nested property like items[0].meta.description, the following approach won't work:

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); 
});
登入後複製

It removes all properties in the targeted array index and only keeps the description property.

Rewriting the entire object also isn't desirable:

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); 
});
登入後複製

It converts the entire items array into an object.

Instead, read the array from the document, make changes in memory, and update the entire modified array field:

const docRef = firestore.collection('collection').doc('document');

docRef.get().then(doc => {
  const items = doc.data().items;

  items[0].meta.description = "hello bar";

  docRef.update({
    items: items
  });
});
登入後複製

This ensures only the intended property is updated in the array element.

以上是如何更新 Firestore 中陣列欄位中的單一項目?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板