在Firestore中添加文档后获取文档ID

时间:2020-08-14 17:00:24

标签: android firebase google-cloud-firestore

aftwe谨慎地使用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?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

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数据库:

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