【问题标题】:Get document id after adding a document in Firestore在 Firestore 中添加文档后获取文档 ID
【发布时间】:2020-12-04 14:17:35
【问题描述】:

仔细阅读this。我仍然无法获得文档自动生成的 ID。没有“那么”选项。 我的代码:

var mFirestore = FirebaseFirestore.getInstance()
mFirestore.firestoreSettings = FirebaseFirestoreSettings.Builder().build()

val rls: MutableMap<String, Any> = HashMap()
rls["title"] = "some data"

var pop = mFirestore.collection("Users").document("mic").collection("Rls")
pop.add(rls)

创建后如何获取ID?

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    您可以执行以下操作:

    var docID = mFirestore.collection("Users").document("mic").collection("Rls").document()
    

    上面会生成一个随机的文档id,然后在添加数据的时候可以这样做:

    var pop = mFirestore.collection("Users").document("mic").collection("Rls").document(docID.id)
    pop.set(rls)
    

    【讨论】:

      【解决方案2】:

      正如here 解释的那样,为了让firestore 自动生成一个id,你可以像这样使用'add' 函数:

      // Add a new document with a generated id.
      val data = hashMapOf(
              "name" to "Tokyo",
              "country" to "Japan"
      )
      
      db.collection("cities")
          .add(data)
          .addOnSuccessListener { documentReference ->
              Log.d(TAG, "DocumentSnapshot written with ID: ${documentReference.id}")
          }
          .addOnFailureListener { e ->
              Log.w(TAG, "Error adding document", e)
          }
      

      然后您可以从“documentReference”.id 中检索“addOnSuccessListener”中的 id。

      编辑: 确保像this一样初始化你的firestore db:

      // Access a Cloud Firestore instance from your Activity
      val db = Firebase.firestore
      

      【讨论】:

        猜你喜欢
        • 2018-12-05
        • 2018-09-03
        • 2018-07-22
        • 1970-01-01
        • 2021-06-11
        • 2018-09-24
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多