【问题标题】:Is It Possible To Get The ID Before It Was Added?是否可以在添加之前获取 ID?
【发布时间】:2018-04-01 09:03:54
【问题描述】:

我知道在Realtime Database 中,我可以在像这样添加之前获得push ID

 DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
 String challengeId=databaseReference.push().getKey();

然后我可以使用此 ID 添加它。

我也可以在Cloud Firestore?得到它

【问题讨论】:

    标签: firebase google-cloud-platform google-cloud-firestore


    【解决方案1】:

    documentation 对此进行了介绍。请参阅添加文档部分的最后一段。

    DocumentReference ref = db.collection("my_collection").doc();
    String myId = ref.id;
    

    【讨论】:

    • 同样的事情发生在我身上......在firestore中.document()并没有给人以与push()相同的数据库通信的印象。我相信一般的观点是,身份冲突的可能性很小,我们不必担心。
    • @krv 我看不出 .doc() 对您不起作用...您可以验证的两件事是 1) 您使用的是 sdk/library/language 的正确方法名称. java 中的 .document(),typescript/javascript 中的 .doc()。 2)您在集合引用而不是文档引用上调用 .doc() 。好勇气!
    • 通过 this.db.collection('collections').ref.doc().id 使用 angularFire2 使其工作
    • 谢谢@krv!这正是我需要做的。你是怎样找到它的?我发现 angularFire 的文档太短了,而且 Firebase 的 API 与 AngularFire 有点不同。
    • 我已更新此答案以替换旧的 api。
    【解决方案2】:
    const db = firebase.firestore();
    const ref = db.collection('your_collection_name').doc();
    const id = ref.id;
    

    【讨论】:

    • 请解释你的答案,不要只是转储代码
    • 我正在使用 vue-fire,这个对我有用。谢谢。
    • @SterlingArcher 有什么要解释的?诚实的问题。
    • @Ruan 很久以前有人告诉我的一个典型考虑是“如果不需要解释,那将是一个问题”。在此基础上,我们假设在回答问题后,通常需要解释为什么来帮助学习
    • @Ruan * 这是如何工作的 * 它仅适用于自动生成的键 * 它是否适用于事务 * 我会在执行更新之前或之后获得一个值 * 这个答案是最新的吗,或者发生了什么变化。根据经验,请不要在没有引用来源或解释的情况下发布 sn-ps
    【解决方案3】:

    您可以通过以下方式执行此操作(代码适用于 AngularFire2 v5,类似于任何其他版本的 firebase SDK,例如 web、node 等)

    const pushkey = this.afs.createId();
    const project = {' pushKey': pushkey, ...data };
    this.projectsRef.doc(pushkey).set(project);
    

    projectsRef 是 firestore 集合引用。

    data 是一个对象,其中包含您要上传到 Firestore 的键、值。

    afs 是在构造函数中注入的 angularfirestore 模块。

    这将在 Collection 中生成一个名为 projectsRef 的新文档,其 id 为 pushKey,并且该文档的 pushKey 属性与文档的 id 相同。

    记住,set 也会删除任何现有数据

    其实 .add() 和 .doc().set() 是相同的操作。但是使用 .add() 会自动生成 id,使用 .doc().set() 您可以提供自定义 id。

    【讨论】:

    • 根据新的 angularFire 更新,这不起作用 this.afs.createId();
    【解决方案4】:

    最简单且更新的(2019 年)方法是主要问题的正确答案:

    “是否可以在添加之前获取 ID?”

    // Generate "locally" a new document in a collection
    const document = yourFirestoreDb.collection('collectionName').doc();
    
    // Get the new document Id
    const documentUuid = document.id;
    
    // Sets the new document (object that you want to insert) with its uuid as property
    const response = await document.set({
          ...yourObjectToInsert,
          uuid: documentUuid
    });
    

    【讨论】:

      【解决方案5】:

      IDK 如果这有帮助,但我想从 Firestore 数据库中获取文档的 ID - 即已经输入到控制台的数据。

      我想要一种简单的方法来即时访问该 ID,因此我只是将其添加到文档对象中,如下所示:

      const querySnapshot = await db.collection("catalog").get();
            querySnapshot.forEach(category => {
              const categoryData = category.data();
              categoryData.id = category.id;
      

      现在,我可以访问id,就像访问任何其他属性一样。

      IDK 为什么 id 首先不只是 .data() 的一部分!

      【讨论】:

      • 想知道这样做是否是个好习惯。除了简化数据模型的客户端使用之外,这肯定是有意义的
      • 自从我看到这个已经有一段时间了,但我不知道这种方法有什么“坏”。
      【解决方案6】:

      Firebase 9

      doc(collection(this.afs, 'posts')).id;
      

      【讨论】:

        【解决方案7】:

        很遗憾,这不起作用:

        let db = Firestore.firestore()
        
        let documentID = db.collection(“myCollection”).addDocument(data: ["field": 0]).documentID
        
        db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])
        

        它不起作用,因为第二条语句在 documentID 完成获取文档 ID 之前执行。因此,您必须等待 documentID 完成加载,然后才能设置下一个文档:

        let db = Firestore.firestore()
        
        var documentRef: DocumentReference?
        
        documentRef = db.collection(“myCollection”).addDocument(data: ["field": 0]) { error in
            guard error == nil, let documentID = documentRef?.documentID else { return }
        
            db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])
        }
        

        这不是最漂亮的,但它是做你所要求的唯一方法。此代码在Swift 5

        【讨论】:

          【解决方案8】:

          你可以在飞镖中使用:

          `var itemRef = Firestore.instance.collection("user")
           var doc = itemRef.document().documentID; // this is the id
           await itemRef.document(doc).setData(data).then((val){
             print("document Id ----------------------: $doc");
           });`
          

          【讨论】:

            【解决方案9】:

            对于 node.js 运行时

            const documentRef = admin.firestore()
              .collection("pets")
              .doc()
            
            await admin.firestore()
              .collection("pets")
              .doc(documentRef.id)
              .set({ id: documentRef.id })
            

            这将创建一个具有随机 ID 的新文档,然后将文档内容设置为

            { id: new_document_id }
            

            希望能很好地解释这是如何工作的

            【讨论】:

              【解决方案10】:

              在 Python 上保存后获取 ID:

              doc_ref = db.collection('promotions').add(data)
              return doc_ref[1].id
              

              【讨论】:

                【解决方案11】:

                docs for generated id

                我们可以在文档中看到doc() 方法。他们将生成新的 ID 并基于它创建新的 ID。然后使用set()方法设置新数据。

                try 
                {
                    var generatedID = currentRef.doc();
                    var map = {'id': generatedID.id, 'name': 'New Data'};
                    currentRef.doc(generatedID.id).set(map);
                }
                catch(e) 
                {
                    print(e);
                }
                

                【讨论】:

                  【解决方案12】:

                  这对我有用。我在同一事务中更新文档。我创建文档并立即使用文档 ID 更新文档。

                          let db = Firestore.firestore().collection(“cities”)
                  
                          var ref: DocumentReference? = nil
                          ref = db.addDocument(data: [
                              “Name” : “Los Angeles”,
                              “State: : “CA”
                          ]) { err in
                              if let err = err {
                                  print("Error adding document: \(err)")
                              } else {
                                  print("Document added with ID: \(ref!.documentID)")
                                  db.document(ref!.documentID).updateData([
                                      “myDocumentId” : "\(ref!.documentID)"
                                  ]) { err in
                                      if let err = err {
                                          print("Error updating document: \(err)")
                                      } else {
                                          print("Document successfully updated")
                                      }
                                  }
                              }
                          }
                  

                  找到一种更清洁的方法会很好,但在那之前这对我有用。

                  【讨论】:

                    【解决方案13】:

                    在节点中

                    var id = db.collection("collection name").doc().id;
                    

                    【讨论】:

                      【解决方案14】:

                      适用于新的 Firebase 9(2022 年 1 月)。就我而言,我正在开发一个 cmets 部分:

                      const commentsReference = await collection(database, 'yourCollection');
                      await addDoc(commentsReference, {
                        ...comment,
                        id: doc(commentsReference).id,
                        date: firebase.firestore.Timestamp.fromDate(new Date())
                      });
                      

                      doc() 包装集合引用(commentsReference)提供了一个标识符(id

                      【讨论】:

                        【解决方案15】:

                        您可以使用辅助方法来生成类似 Firestore 的 ID,然后调用 collection("name").doc(myID).set(dataObj) 而不是 collection("name").add(dataObj)。如果 ID 不存在,Firebase 会自动创建文档。

                        辅助方法:

                        /**
                         * generates a string, e.g. used as document ID
                         * @param {number} len length of random string, default with firebase is 20
                         * @return {string} a strich such as tyCiv5FpxRexG9JX4wjP
                         */
                        function getDocumentId (len = 20): string {
                          const list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                          let res = "";
                          for (let i = 0; i < len; i++) {
                            const rnd = Math.floor(Math.random() * list.length);
                            res = res + list.charAt(rnd);
                          }
                          return res;
                        }
                        

                        用法:const myId = getDocumentId()

                        【讨论】:

                          猜你喜欢
                          • 2022-11-24
                          • 2011-10-11
                          • 2016-04-11
                          • 1970-01-01
                          • 1970-01-01
                          • 2020-06-16
                          • 1970-01-01
                          • 1970-01-01
                          • 2010-10-16
                          相关资源
                          最近更新 更多