I have a Firestore collection of users in which I am storing the data of my application users. Each individual user has their personal details. Now I am trying to add a sub-collection to my existing user document but it is getting added as a new document.
here’s what I am doing.
const communityValue = {
communityName: "",
communityType: "public",
}
const communityDocRef = doc(
firestore,
"communities",
communityValues.communityName
);
const communityDoc = await getDoc(communityDocRef);
await setDoc(communityDocRef, {
creatorId: user?.uid,
createdAt: serverTimestamp(),
numberOfMembers: 1,
privacyType: communityValues.communityType,
});
await setDoc(doc(firestore,`users/${user.uid}/community-details`,communityValues.communityName),{
id: communityValues.communityName,
isModerator: true,
});
The first entry DKh76N4FLChbbRb1grzL
is the existing user in which i am trying to add community-details but community-details collection is getting added as a separate document.
2
Answers
The
user.uid
returns the ID of the authenticated user. So when you create the following reference:You’ll get in the database the following result:
If you want to create a sub-collection under the first document (DKh76N4FLChbbRb1grzL) then you have to create a reference that contains that ID:
But please note, that this ID is not an ID that comes from an authentication process, but an ID that is generated by Firestore. So when you write the first document, explicitly specify
${user.uid}
to the doc() function, otherwise, as it will generate a new random ID, each time you call it.