want to create a subcollection in document in firebase when user sign up to app in react native its children subcollection created

want to add a subcollection when the user signs up to the app a subcollection is created to its document which contains its children.
here is my code:

    try {
    await firebase.auth().createUserWithEmailAndPassword(email, password);
    const currentUser = firebase.auth().currentUser;

    const db = firebase.firestore();
    db.collection("users")
      .doc(currentUser.uid)
      .set({
        email: currentUser.email,
        lastName: lastName,
        firstName: firstName,
        
      }).collection('users').doc(currentUser.uid).collection("recipient").add({name:"test", age:"25" }).then((data) => {
        console.log(data.id);
        console.log("Document has added")
    }).catch((err) => {
        console.log(err)
    })
    
  } catch (err) {
    alert("There is something wrong!!!!" + err.message.toString());
  }
}

7 thoughts on “want to create a subcollection in document in firebase when user sign up to app in react native its children subcollection created”

  1. The problem in your code is linked second add document to sub-collection because the first promise does not return the document reference but a sort of information about how long operation was taken. The right approach will be the following:

    async function addUser(id, user) {
        const db = firebase.firestore();
        const users = db.collection('users')
    
        try {
          const result = await users.doc(id).set(user)
          return result
    
        } catch (e) {
    
          console.log("addUser: ", e)
          return null
        }
        
    }
    
    async function getUserRef(id) {
        const db = firebase.firestore();
        const users = db.collection('users')
       
        try {
          const docSnapshot = await users.doc(id).get()
          return docSnapshot.ref
    
        } catch (e) {
    
          console.log("getUserRef: ", e)
          return null
        }
    }
    
    try {
       const user = {
           email: currentUser.email,
           lastName: lastName,
           firstName: firstName,
       }
       const result = await addUser(id, user);
       const ref = await getUserRef(id)
       await ref.collection("recipient").add({name:"maham", age:"25" })
    } catch (e) {
        console.log(e)
    }
    
    Reply

Leave a Comment