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()
}
}
}
2
Answers
After receiving Alex Mamo's response, I modified my code as follows:
.update("guests.$guestId", guest)
When you’re using
FieldValue.arrayUnion(guest)
it means that you try to add a new element inside an array. Those numbers0
and1
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:
To achieve this, you have to use the
update()
function, but without telling Firestore to add that to the guestarray
. See, the key of the first object is the ID that you’re looking for.