Problem Statement:
You have a document in Firestore with an array field containing objects. You need to update a specific field within an object inside the array. However, attempting to update directly using the dot notation (items.${index}.meta.description) doesn't work correctly.
Firestore does not currently support directly updating a specific element in an indexed array. Instead, consider the following alternatives:
Option 1: Rewrite the Entire Array
Instead of updating the specific field, read the entire array from the document, make the desired modification in memory, then update the modified array field as a whole:
const key = `items.${this.state.index}.meta`; let items = this.state.items; items[this.state.index].meta.description = 'hello bar'; this.design.update({ [key]: items, })
This approach effectively rewrites the entire array, which may be inefficient if the array is large.
Option 2: Use Array Operations
While Firestore doesn't allow direct updates to existing array elements, you can still add or remove elements using array operations. For example, to append a new element to the array:
this.design.update({ items: FieldValue.arrayUnion({ name: 'New Item', meta: { image: 'def.png', description: 'hello new item', } }) })
To remove an element, use FieldValue.arrayRemove().
Recommendation:
If the array is relatively small, Option 1 (rewriting the entire array) can be a straightforward solution. However, if the array is large, Option 2 (using array operations) is more efficient as it avoids overwriting the entire array.
以上がFirestore で配列内のネストされたフィールドを更新するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。