skip to Main Content

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,
         });

enter image description here

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


  1.    import { child, getDatabase, set, ref, update } from "firebase/database";  
       const dbRef = ref(getDatabase());
       // i used userId as key. userId:communityDetails
       const childRef = child(dbRef, `users/${userId}`);
       // then you can either update it. create newUserDetailData
       await update(childRef, newUserDetailData);
       // or add a new user userDetailsData. create `userDetailsData`
       await set(childRef, userDetailsData);
    
    Login or Signup to reply.
  2. The user.uid returns the ID of the authenticated user. So when you create the following reference:

    users/${user.uid}/community-details
    

    You’ll get in the database the following result:

    db/RmyX...YQI3/community-details
    

    If you want to create a sub-collection under the first document (DKh76N4FLChbbRb1grzL) then you have to create a reference that contains that ID:

    `users/DKh76N4FLChbbRb1grzL/community-details`
    //           👆
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search