如何在Firestore中向嵌套文档中添加数据

huangapple go评论69阅读模式
英文:

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 名称。

我得到的结果 - 如何在Firestore中向嵌套文档中添加数据
如何在Firestore中向嵌套文档中添加数据

英文:

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

Results I got - 如何在Firestore中向嵌套文档中添加数据
如何在Firestore中向嵌套文档中添加数据

答案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);

huangapple
  • 本文由 发表于 2023年6月19日 22:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定