I am trying to add data to my firestore database. The firestore is this:
Firestore db
I have my php file that loads data into it with this code db.collection('events').doc('documentNameUsingUniqueEventID').set({id1:data1, id2:data2, id3:data3, ...});
but when I load new data and old still exists the documents gets overwrite and I lose the changes I made. Is there a way to add data avoiding overwrite existing ones?
Yes, this is possible using a combination of two collections, Firestore rules and batched writes. The simple idea is, using a batched write, you write your document to your "data" collection and at the same write to a separate "index" collection where you index the value of the field that you want to be unique.
Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.
When it comes to the official documentation regarding how to update elements in an array in Firestore, it says that: If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present.
The set() method on DocumentReference has a second parameter for SetOptions that allows you to say that you want to merge data into an existing document rather than overwrite it:
db.collection('events')
.doc('documentNameUsingUniqueEventID')
.set(data, { merge: true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With