英文:
How to add data in nested document in firestore
问题
我想要构建一个集合,使得 "mainCollection" => "Client" => "Location" => { ...data }。Client 和 Location 有 Client 名称和 Location 作为 ID。我想要在这个集合中添加数据,并使用以下代码:
const docRef = await addDoc(
collection(db, "mainCollection", "Client", "Location"),
{
...data
}
);
console.log(docRef.id);
这将生成一个 ID,我希望 ID 保持为 Location 名称。
英文:
I want to structure a collection such that "mainCollection" => "Client" => "Location" => { ...data } . Client and Location have Client name and Location as IDs . I wanted to add data in this collection , and used
const docRef = await addDoc(
collection(db, "mainCollection", "Client","Location"),
{
...data
}
);
console.log(docRef.id);
which generated an id , I want to do it in such a way that id remains Location name
答案1
得分: 1
你可以按照以下方式将数据设置到文档ID所在位置:
firestore.doc(`/mainCollection/${clientDocID}/${locationColId}/${locationDocID}`).set({
... 你的数据
}, {
merge: true // 如果不需要合并,可以删除这些括号
})
或者如果你想要动态ID:
const docRef = firestore.collection(`/mainCollection/${clientDocID}/${locationColId}/`).add({
... 你的数据
})
console.log('添加了带有ID的文档:', docRef.id)
英文:
You can set data into location doc ID as following:
firestore.doc(`/mainCollection/${clientDocID}/${locationColId}/${locationDocID}`).set({
... your data
}, {
merge: true // you can remove these brackets if you don't need merge
})
Or if you want dynamic IDs:
const docRef = firestore.collection(`/mainCollection/${clientDocID}/${locationColId}/`).add({
... your data
})
console.log('Added document with ID: ', docRef.id)
答案2
得分: 1
使用 setDoc
时已在 docRef
中包括了文档 ID。需要记住的一点是,如果文档已经存在,setDoc
会覆盖该文档。而 addDoc
会自动分配文档 ID。
const location = "California";
const docRef = doc(db, "mainCollection", "Client", "Location", location);
await setDoc(docRef, { ...data });
console.log(docRef.id);
英文:
use setDoc
with the document id already included in the docRef. One thing to keep in mind that setDoc will override the doc if already exist. While, addDoc
auto assigns the document id.
const location="California";
const docRef =doc(db, "mainCollection", "Client", "Location", location);
await setDoc(docRef, { ...data});
console.log(docRef.id);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论