如何创建自动生成的文档ID本身的字段?

时间:2020-05-05 08:58:19

标签: android firebase kotlin google-cloud-firestore

我想创建一个继承了该字段的文档ID的字段。

val fStore: FirebaseFirestore = FirebaseFirestore.getInstance()
                val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
                val post = Post(title, description , publisherId = currentUserId)
                fStore.collection("Posts")
                        .add(post)
                        .addOnSuccessListener{
                         Toast("Your post has been uploaded successfully.")
                        }

与上面的代码一样,我将currentUserId的字段设置为publisherId, 换句话说:

example of firestore

1 个答案:

答案 0 :(得分:2)

有两种方法可以解决此问题。一种方法是使用currentUserId作为文档的键,然后使用set()代替add()

val fStore: FirebaseFirestore = FirebaseFirestore.getInstance()
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
val post = Post(title, description , publisherId = currentUserId)
fStore.collection("Posts")
        .document(currentUserId)
        .set(post)
        .addOnSuccessListener{
            Toast("Your post has been uploaded successfully.")
        }

这是一个更常见的解决方案,因为您使用的是来自身份验证过程的用户ID(而不是随机密钥)作为文档的密钥。您拥有的第二个选项是使用Firestore生成的ID:

val fStore: FirebaseFirestore = FirebaseFirestore.getInstance()
val key = fStore.collection("Posts").document().id;
val post = Post(title, description , publisherId = key)
fStore.collection("Posts")
        .document(key)
        .set(post)
        .addOnSuccessListener{
            Toast("Your post has been uploaded successfully.")
        }

在两种情况下,要使文档ID和publisherId具有相同的值,则应使用set()和 add(),因为add()始终每次调用都会生成一个随机id。

编辑:

set()的作用与add()完全相同,唯一的区别是您需要在实际使用ID之前先知道它。因此,在您的情况下,您应该使用第二种解决方案。

如果您只想将帖子ID作为属性添加到文档中,则应通过添加另一个名为Post的字段来更改postId类。现在,当您要创建一个新的Post对象并将其添加到数据库中时,请使用以下代码行:

val fStore: FirebaseFirestore = FirebaseFirestore.getInstance()
val key = fStore.collection("Posts").document().id;
val post = Post(title, description , publisherId = key, postId) //postId added
fStore.collection("Posts")
        .document(key)
        .set(post)
        .addOnSuccessListener{
            Toast("Your post has been uploaded successfully.")
        }

看,我已经将文档ID的值传递给了构造函数,该ID实际上是帖子ID。现在,每次添加新帖子时,始终将帖子ID作为文档的属性。