[英]Firestore - get auto-generated id from added object
I was not able to find a solution for that problem. 我找不到该问题的解决方案。 All I do is inserting a custom object to my Firestore database. 我要做的就是将自定义对象插入Firestore数据库。 After the data is successfully inserted, I would like to get the id of the inserted object. 成功插入数据后,我想获取插入对象的ID。 Is that possible? 那可能吗?
var group : Group = Group("test")
firestore.collection("groups").add(group).addOnCompleteListener(OnCompleteListener {
//get id
})
Yep. 是的 It'll be something like 就像
OnCompleteListener { val id = it.result.id }
Basically, the on complete method (you'll want to check if its successful in here btw) should give you a document object in the callback which you can get the id from! 基本上,on complete方法(您将在这里btw检查它是否成功)应该在回调中为您提供一个文档对象,您可以从中获取ID!
If you want to get the id of document while adding it to the database, please use the following code: 如果要在将文档ID添加到数据库时获取其ID,请使用以下代码:
val rootRef = FirebaseFirestore.getInstance()
val groupsRef = rootRef.collection("groups")
val group = Group("test")
val id = groupsRef.document().id //Get the document id
groupsRef.document(id).set(group).addOnSuccessListener {
Log.d("TAG", "The document with " + id + " was successfully added!")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.