Home > OS >  Adding a map to an array on Firestore Android
Adding a map to an array on Firestore Android

Time:11-14

I'm having a little trouble getting my data to save to a Firestore database. Each document in my "meetings" collection has a list of users (maps), but I cannot seem to add anything or create a new document. I read the documentation, and it said to use FieldValue.arrayUnion(), which I tried:

    private fun addUserToMeeting(user: User) {
        val meetingRef = database.collection("meetings").document(meetingID.toString())

        val userData = hashMapOf(
            "email" to user.email,
            "latitude" to user.latitude,
            "longitude" to user.longitude,
            "token" to user.token,
            "username" to user.username
        )

        meetingRef.update("users", FieldValue.arrayUnion(userData))
    }

This is called anytime an "add user to meeting" button is clicked.

Here's a picture of my schema: enter image description here

Has anyone got some suggestions on what I might be doing wrong?

CodePudding user response:

If the document doesn't exist yet, you can't use update to create it. As its name implies, update can only be used to update an existing document.

To create a new document at a location you control, use set:

meetingRef.set(hashMapOf("users" to FieldValue.arrayUnion(userData)))

Also see the Firebase documentation on setting a document.

  • Related