[英]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”)。
作為替代方案,您可以從文檔中讀取整個數組,在內存中對其進行修改,然后完全更新修改后的數組字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.