简体   繁体   English

如何在Firestore中获取生成的文档ID,然后在其中添加子集合?

[英]How to get a generated document's ID in the firestore then add subcollection into it?

I am creating a todo-list, and I want to enable users to add the task in the list. 我正在创建一个待办事项列表,并且希望允许用户将任务添加到列表中。 However, I am troubled in getting document id. 但是,我在获取文档ID时遇到了麻烦。

Here are 2 methods I have tried: 这是我尝试过的2种方法:

 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")

Unlucky, this way createe a new document insteading of storing task into the list. 不幸的是,这种方式创建了一个新文档,而不是将任务存储到列表中。

Another method is: 另一种方法是:

        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")

But it said listId is undefined. 但它说listId是未定义的。

Here is my firebase structure: 这是我的firebase结构:

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

Amy suggestions? 艾米的建议? Thanks a lot! 非常感谢!

In order to get the document's ID I would suggest you take a look at this answer . 为了获得文档的ID,建议您看一下这个答案 Also maybe this may prove helpful. 同样也许可能会有所帮助。 As for adding a subcollection to a document I would suggest you reading this question and the following documentation . 至于向文档中添加子集合,我建议您阅读此问题和以下文档

Let me know if these were helpful. 让我知道这些是否有帮助。

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

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