首页 > 解决方案 > 如何在 Firestore 中获取生成的文档 ID,然后将子集合添加到其中?

问题描述

我正在创建一个待办事项列表,并且我想让用户能够在列表中添加任务。但是,我在获取文档 ID 时遇到了麻烦。

以下是我尝试过的两种方法:

 this.currentUser = firebase.auth().currentUser;
        const currentUserUid = this.currentUser.uid;
        let collectionPath = "/userProfile/" + currentUserUid  + "/list";

        this.list = firebase.firestore().collection(collectionPath).doc()
        const listId = this.list.id; 

        this.ref = firebase.firestore().collection(collectionPath)
                  .doc(listId).collection("task")

不幸的是,这种方式创建了一个新文档,而不是将任务存储到列表中。

另一种方法是:

        this.currentUser = firebase.auth().currentUser;
        const currentUserUid = this.currentUser.uid;
        let collectionPath = "/userProfile/" + currentUserUid  + "/list";

        this.list = firebase.firestore().collection(collectionPath)
                   .get().then((snapshot) => {
                   snapshot.docs.forEach(doc => {
                       return doc.data();                    
                   })
                   })
        const listId = this.list.id; 

        this.ref = firebase.firestore().collection(collectionPath)
                  .doc(listId).collection("task")

但它说 listId 是未定义的。

这是我的火力基地结构:

User(Collection) - User1...
                     |
                   List(Collection) - List1...
                                        |
                             (Expected)Task(Collection) - task1...

艾米的建议?非常感谢!

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


为了获得文档的 ID,我建议您看一下这个答案。也许可能会有所帮助。至于将子集合添加到文档中,我建议您阅读此问题和以下文档

让我知道这些是否有帮助。


推荐阅读