I have two Activities, I am adding data to Firestore from these two activities individually. But, whenever I add second activity data to Firestore, it is overwriting the first activity data. I used below code in the two activities:
firebaseFirestore.collection("Users").document(user_id).set(data)
How to stop overwriting? I want to save both Activities data in the same user_id
.
I suggest you to add one more document or collection that it will be able to store more just one data values for single user.
You can create a document references for both activities:
Or you can create a sub-collection for it:
More about hierarchical data there.
As per the documentation, you could use as a second parameter
{merge:true}
, in my experience the problem usually is in the fact that you are trying to store different data but with the same key.Even using
{merge: true}
will always update the current key with the value you are passing in.Merge:true Works only if the key does not exist already. I believe every key in a document must be unique.
To test it try to pass(keeping
{merge: true}
as the second parameter) data with a different key, it will merge to existing.There are two ways in which you can achieve this. First one would be to use a
Map
:As you can see, I have used
update()
method instead ofset()
method.The second approach would be to use an object of your model class like this:
As you can see, I have used the
set()
method but I have passed as the second argumentSetOptions.mergeFields("yourProperty")
, which means that we do an update only on a specific field.If you know that the user document allready exists in firestore then you should use
If you don't know if the document exists then you can use
This performs a deep merge of the data
Alternatively you can do it by using subcollections