[英]Updating a map field in firestore
I'm newbie and just starting coding a couple of months ago.我是新手,几个月前才开始编码。 I'm creating an app with react native with expo and I'm having trouble updating a map field into the document.
我正在创建一个带有 expo 原生反应的应用程序,但我无法将 map 字段更新到文档中。 So far, when I needed to update a filed(for example a name) I was doing the following:
到目前为止,当我需要更新一个文件(例如一个名字)时,我正在做以下事情:
const updateData = async () => {
await updateDoc(doc(db,"users",uid),{
name:name,
age: age,
})
The problem is that I now have a map field which stores data in the following way:问题是我现在有一个 map 字段,它按以下方式存储数据:
The way that I have the app set-up, is that I have an array for the food items:我设置应用程序的方式是,我有一个食物数组:
const [item, setItem] = useState([
{Food: 'tomato', Calories: 20, Quantity: 1,},
{Food: 'lettuce', Calories: 10, Quantity: 1,},
]);
and I would like to store it into a map field in the firestore document.我想将它存储到 firestore 文档中的 map 字段中。
I thought that I would be able to use a for loop, so that I can populate each field of an array element into the map, but it seems that I'm unable to use a loop inside the await.我以为我可以使用 for 循环,这样我就可以将数组元素的每个字段填充到 map 中,但似乎我无法在 await 中使用循环。
Is there like a workaround that I would be able to use in this case?在这种情况下,我可以使用类似的解决方法吗?
The for loop that is being highlighted in red:以红色突出显示的 for 循环:
await updateDoc(doc(db,"user",uid),{
for (let i = 0; i < item.length; i++) {
}
},
{ merge: true })
To convert the array into a map, try using reduce()
as shown below:要将数组转换为 map,请尝试使用
reduce()
,如下所示:
const updatedMap = item.reduce((a, b) => {
a[b.Food] = b;
return a;
}, {})
await updateDoc(doc(db, "user", uid), { food: updatedMap })
This will use food name as key in food map and test of the object as value.这将使用食物名称作为食物 map 中的键,并将 object 的测试作为值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.