Home > Enterprise >  How do you add extra data to a document in firestore in kotlin?
How do you add extra data to a document in firestore in kotlin?

Time:05-05

This is how I add data to my Firestore, hopefully it gives you an idea of how my database looks like:

val postMap = hashMapOf(
                            "date" to currentDate,
                            "publisher" to userID,
                            "postImage" to myUrl,
                            "caption" to binding.etCaption.text.toString().lowercase(),
                            "rent" to binding.etHousePrice.text.toString().lowercase(),
                            "location" to binding.etHouseLocation.text.toString().lowercase(),
                            "rooms" to binding.etNumberOfRooms.text.toString().lowercase(),
                            "description" to binding.etPostDescription.text.toString().lowercase()
                        )

I want to add another piece of data as follows but later on

                                val data = hashMapOf("post_id" to id)

How do I achieve that without overwriting the existing data?

CodePudding user response:

To add the following data later, to an existing document, please use the following lines of code:

val data = hashMapOf("post_id" to id)
val db = Firebase.firestore
val postsRef = db.collection("posts")
val postIdRef = postsRef.document(postId)
postIdRef.update(data)

More details are below:

https://firebase.google.com/docs/firestore/manage-data/add-data#update-data

As the docs states, you can also attach a failure lister, to always see if something goes wrong.

CodePudding user response:

private var userMap: HashMap<String, Any> = HashMap() 
userMap["post_id"] = id
val collection = Firebase.firestore.collection("posts")
        collection.document(postId)
            .update(userMap)
            .addOnSuccessListener {
                //succes update message
            }
            .addOnFailureListener {
                //failure update message
            }
  • Related