Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore add data without overwrite

I am trying to add data to my firestore database. The firestore is this:

Firestore db

enter image description here

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?

like image 780
Dennis Avatar asked Feb 05 '18 16:02

Dennis


People also ask

How do I add unique data to firestore?

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.

How do I increment a field in firestore?

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.

Can I add to an array firestore?

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.


1 Answers

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 });
like image 66
Doug Stevenson Avatar answered Nov 15 '22 21:11

Doug Stevenson