简体   繁体   English

想要在 firebase 中的文档中创建一个子集合,当用户注册到应用程序时反应原生它的子集合创建

[英]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());
  }
}

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.您的代码中的问题与第二个将文档添加到子集合相关联,因为第一个 promise 不返回文档引用,而是返回有关操作花费了多长时间的信息。 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:"test", age:"25" })
} catch (e) {
    console.log(e)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM