如何使用 Firebase 在 Kotlin 中自动生成 ID?

问题描述 投票:0回答:1

如何为客人添加自动生成的ID?例如,如下图所示,我有两个客人,第一个ID=0,第二个ID=1。我想删除编号的 ID 并添加生成的 ID。

我的功能:

fun saveToFirebase(
 guest: MutableMap<String, Any>,
 eventId: String,
 navController: NavController,
 local: Context) {

  val db = FirebaseFirestore.getInstance()
  val dbCollectionEvents = db.collection(COLLECTION_EVENTS)

  if (guest.toString().isNotEmpty()) {
    // Update the document with the new data
    dbCollectionEvents.document(eventId)
        .update(GUESTS, FieldValue.arrayUnion(guest))
        .addOnSuccessListener {
            // Document updated successfully
            Toast.makeText(
                local,
                "Guest added",
                Toast.LENGTH_SHORT
            ).show()
        }
        .addOnFailureListener { e ->
            // Handle failures
            Log.w("ERROR", "saveToFirebase: Error add guest", e)
            Toast.makeText(
                local,
                "Guest addition not functioning",
                Toast.LENGTH_SHORT
            ).show()
        }
   }
}

android firebase kotlin google-cloud-platform google-cloud-firestore
1个回答
0
投票

当您使用

FieldValue.arrayUnion(guest)
时,这意味着您尝试在数组中添加新元素。这些数字
0
1
实际上是索引,更准确地说,是数组的第一个和第二个索引。

如果您需要使用 ID 而不是这些索引,那么您必须将这些来宾添加为文档内的对象,而不是数组内的对象。这是一个例子:

db
|
--- events (collection)
     |
     --- eventId (document)
          |
          --- guests (map)
               |
               --- 8ac6c1d0-55e2-4130-b247-3b1b005bcd39
                    |
                    --- adults: 2
                    |
                    --- date_registered: 29 March 2024 at 22:50:09 at UTC+2
                    |
                    --- //The other fields

要实现此目的,您必须使用

update()
函数,但不告诉 Firestore 将其添加到来宾
array
。看,第一个对象的键就是您要查找的 ID。

© www.soinside.com 2019 - 2024. All rights reserved.