简体   繁体   English

Firestore-从添加的对象获取自动生成的ID

[英]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.

相关问题 通过自动生成的文档ID从Firestore中删除文档 - Deleting a document from Firestore via Auto-generated document ID 如何使用自动生成的文档 ID 从 android 中的 Firestore 中删除项目 - How to delete Item from firestore in android with auto-generated document ID JPA如何获取自动生成的持久对象ID? - How does JPA gets auto-generated ID of persisted object? 从Oracle数据库检索Java代码中的自动生成的ID - Retrieve Auto-Generated ID in Java Code From Oracle DataBase 文档的路径与Firestore自动生成的随机ID有关系吗? - Does the path of a Document have any bearing on the random ID auto-generated by Firestore? 如何在PreparedStatement中使用自动生成的@Id? - How to use auto-generated @Id in PreparedStatement? Java:检查自动生成的 ID - Java: Check auto-generated ID MySQL-外键和自动生成的ID - MySQL - Foreign key and auto-generated ID 休眠:如何使用父对象的自动生成的ID作为外键来级联嵌入式对象 - Hibernate: How to cascade embedded objects with parent object's auto-generated ID as a foreign key 如何在使用JPA时有效地找到新对象的自动生成的id? - How to find out efficiently the auto-generated id for a new object when using JPA?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM