【问题标题】:auto generate id for document and not collection in firestore为文档自动生成 ID,而不是在 Firestore 中收集
【发布时间】:2018-10-19 21:48:06
【问题描述】:

我已经浏览了 firestore 文档,但我还没有找到一个我们有这样的例子。

collection
       |--document
                |--{auto-generated-id}
                                  |--property1:value1
                                  |--property2:value2
                                  |--peoperty3:value3

而我经常看到的是:

collection     
         |--{auto-generated-id}
                            |--property1:value1
                            |--property2:value2
                            |--peoperty3:value3

在前者中,我不能在文档上调用add()-(生成唯一ID)。但是,这可以在集合中完成,如上面后一个草图所示。

我的问题是: 有没有办法firestore可以在创建文档后帮助自动生成一个id IE 我怎样才能实现这样的目标:

db.collection("collection_name").document("document_name").add(object)

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    如果你使用的是 CollectionReference 的add() 方法,那就意味着它:

    以指定的 POJO 作为内容向此集合添加一个新文档,并自动为其分配一个文档 ID。

    如果要获取生成的文档 id 并在参考中使用,请使用 DocumentReference 的 set() 方法:

    覆盖此 DocumentRefere 引用的文档

    如下代码行:

    String id = db.collection("collection_name").document().getId();
    db.collection("collection_name").document(id).set(object);
    

    【讨论】:

    • 是的! @Alex Mamo,您的解决方案非常有帮助。我所做的只是创建一个新集合并调用 add 即 db.collection("new_collection_name").add()...
    • 真的很有帮助。虽然,你的回答总是简短、甜蜜和乐于助人。非常感谢。
    • .document() 方法似乎不再存在 - 目前的建议是使用 doc(),它将创建一个 DocRef,然后获取 .id 属性。
    • @MikeBurton 对于 Android,它仍然是 .document()不是 doc()
    【解决方案2】:

    这个答案可能有点晚,但您可以在此处查看此代码,它将生成一个新的文档名称:

    // Add a new document with a generated id.
    db.collection("cities").add({
        name: "Tokyo",
        country: "Japan"
    })
    .then(function(docRef) {
        console.log("Document written with ID: ", docRef.id);
    })
    .catch(function(error) {
        console.error("Error adding document: ", error);
    });
    

    让 Cloud Firestore 为您自动生成 ID 会更方便。你可以通过调用add()来做到这一点

    Add data to Cloud Firestore了解更多信息

    【讨论】:

      【解决方案3】:

      现在 firebase javascript API 的 v9 已经发布,语法发生了一些变化。

      import { collection, addDoc } from "firebase/firestore"; 
      
      // Add a new document with a generated id.
      const docRef = await addDoc(collection(db, "cities"), {
        name: "Tokyo",
        country: "Japan"
      });
      console.log("Document written with ID: ", docRef.id);
      

      您可以将其包装在 try/catch 块中以处理错误。

      总结:

      • 如果要自动生成 ID,请使用 addDoc() + collection()
      • 如果要设置 ID,请使用 setDoc() + doc()

      【讨论】:

        【解决方案4】:

        由于您已经知道文档的 id,因此只需调用 set() 而不是 add()。如果文档尚不存在,它将创建该文档。

        【讨论】:

          【解决方案5】:

          要在 Flutter/dart 中实现这一点,您可以将 Future 设为 1)。 在 firestore 中创建一个文档(firestore 将自动为该文档生成一个 ID),2)。然后调用创建的文档,3)。最后显示id更新ID字段

          Future createPost(PostModel postModel) async {
            _firestore.collection("posts").add({
          
            "pid": postModel.pid, // Creating a field for post ID
          
            }).then((querySnapshot) { // Here whe call the document just after creation
          
            String generatedID = querySnapshot.id.toString(); // Here we call the ID of the document
          
            print("ID OF CREATE POST: " + generatedID); // Here we display the generated document ID
          
            querySnapshot.update({ // Here we update the pid(Post ID) field in the new generated document
              "pid": generatedID
            });
          });
          

          }

          【讨论】:

            【解决方案6】:

            当您将文档添加到集合中时,响应对象将包含已创建文档的 id。所以你可以在javascript中解构response对象,直接使用这个id。

            (async () => {
               const dataObject = YOUR_DATA;
               const { id } = await firebase.firestore().collection("YOUR_COLLECTION_NAME").add(dataObject);
               console.log(id); //the newly added doc's id
            })()
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-03-29
              • 2018-08-27
              • 2019-09-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-12-19
              相关资源
              最近更新 更多