Home >Web Front-end >JS Tutorial >How to Update a Single Item in an Array Field in Firestore?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 10:02:03509browse

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.

The above is the detailed content of How to Update a Single Item in an Array Field in Firestore?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn