How to Automatically Generate IDs in Kotlin with Firebase?

40 Views Asked by At

How can I add automatically generated IDs to guests? For example, as shown in the picture below, I have two guests, the first one with ID=0 and the second one with ID=1. I want to remove the numbered IDs and add generated IDs instead.

My function:

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()
        }
   }
}

enter image description here

2

There are 2 best solutions below

1
Alex Mamo On

When you're using FieldValue.arrayUnion(guest) it means that you try to add a new element inside an array. Those numbers 0 and 1 are actually indexes, more precisely, the first and the second index of the array.

If you need instead of those indexes to use IDs, then you have to add those guests as objects inside the document and not as objects inside the array. Here is an example:

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

To achieve this, you have to use the update() function, but without telling Firestore to add that to the guest array. See, the key of the first object is the ID that you're looking for.

0
zartilas On

After receiving Alex Mamo's response, I modified my code as follows:

.update("guests.$guestId", guest)

if (guest.toString().isNotEmpty()) {
        // Get the guest_id from Guest model
        val guestId = guest.toMap()["guest_id"]
        // Update the document with the new data
        dbCollectionEvents.document(eventId)
            .update("guests.$guestId", guest)
            .addOnSuccessListener {}
}

enter image description here