如何将自动生成的ID添加到Cloud Firestore数据库

时间:2020-02-26 19:47:21

标签: kotlin google-cloud-firestore

这是我的哈希图,它没有添加实际生成的ID

    val user = hashMapOf(
        "deviceToker" to " ",
        "dob" to date.text.toString(),
        "email" to email_reg.text.toString(),
        "id" to db.collection("patients").document().id,
        "name" to name.text.toString()
    )

2 个答案:

答案 0 :(得分:2)

如果要将文档的随机生成的ID添加到文档本身的内容中,请首先调用不带参数的document(),以获得对尚不存在的文档的引用:

val ref = db.collection("patients").document()

然后使用该引用将ID添加到文档内容:

val user = hashMapOf(
    "deviceToker" to " ",
    "dob" to date.text.toString(),
    "email" to email_reg.text.toString(),
    "id" to ref.id,   // note the use of ref.id here to get the random id
    "name" to name.text.toString()
)

现在使用相同的引用添加文档:

ref.set(user)  // be sure to check for errors

如您所见,该ID是在客户端而非服务器上生成的。

答案 1 :(得分:0)

我认为您使用的程序不正确。从文档中:

// Add a new document with a generated id.
val newCityRef = db.collection("cities").doc();

// later...
newCityRef.set(data);

所以我要怎么做:

  • 首先创建对文档的引用。
  • 然后将数据设置到文档引用中。