[英]How can I add an object to an array inside a Firebase Field Collection?
I'm trying to create a to-do style app.我正在尝试创建一个待办事项风格的应用程序。 I'm trying to create a card that contains a name and tags field.我正在尝试创建一个包含名称和标签字段的卡片。 Here's an example of my data structure.这是我的数据结构的示例。 I want to create another cards array but for id: "nhl".我想创建另一个卡片数组,但要使用 id:“nhl”。
[![enter image description here][1]][1] [![在此处输入图片描述][1]][1]
I want to create a cards array (everything inside the blue box) but for the 1 object with the id:"nhl".我想创建一个卡片数组(蓝色框内的所有内容),但要创建 ID 为“nhl”的 1 object。
Here is what my createCard function looks like:这是我的 createCard function 的样子:
const createCard = async () => {
await updateDoc(doc(db, "users", currentUser.uid), {
labels: arrayUnion({
activeLabel: [
{
name: name,
tags: tags,
},
],
}),
});
getData();
findLabel(activeLabel);
// toast.success("Tags Created!");
console.log("Tags Created");
};
Here is where the function is being called:这是调用 function 的地方:
return (
<div className="cards">
<div className="cards__create">
<input
onChange={(e) => setName(e.target.value)}
className="cards__input"
placeholder="Enter title..."
></input>
<textarea
onChange={(e) => setTags(e.target.value)}
className="cards__input cards__input--textarea"
placeholder="Enter tags..."
></textarea>
<img
onClick={createCard}
className="cards__add"
src={addIcon}
alt="plus sign icon"
></img>
</div>
arrayUnion()
cannot work in your case. arrayUnion()
不适用于您的情况。 As explained in the doc , "each specified element that doesn't already exist in the array will be added to the end."正如文档中所解释的那样,“数组中尚不存在的每个指定元素都将添加到末尾。”
So, instead of updating the second element of the labels array, arrayUnion()
will create a new array element with the same id
fiels id:"nhl"
and the two cards.因此, arrayUnion()
不会更新标签数组的第二个元素,而是会创建一个具有相同id
字段id:"nhl"
和两张卡片的新数组元素。
You need to first read the Firestore document, modify the labels
Array in your front-end and write it back to Firestore.你需要先阅读Firestore文档,修改你前端的labels
数组,然后写回Firestore。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.