Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Add value to array field

Im trying to use Firebase cloud functions to add the id of a chatroom to the users document in an array field. I cant seem to figure out the way to write to an array field type. here is my cloud function

  exports.updateMessages = functions.firestore.document('messages/{messageId}/conversation/{msgkey}').onCreate( (event) => {     console.log('function started');     const messagePayload = event.data.data();     const userA = messagePayload.userA;     const userB = messagePayload.userB;             return admin.firestore().doc(`users/${userA}/chats`).add({ event.params.messageId }).then( () => {          });    }); 

here is the way my database looks

enter image description here

any tips greatly appreciated, Im new to firestore.

like image 763
Kravitz Avatar asked Jan 12 '18 18:01

Kravitz


People also ask

How do I update a field in firestore?

Firestore Update Document Field What if we want to just update a value of a specific field in an existing document. To do that, all we have to do is add a third argument to the setDoc() method. It will be a JavaScript object with a single property: merge:true.

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.


2 Answers

From the docs, they added a new operation to append or remove elements from arrays. Read more here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

Example:

var admin = require('firebase-admin'); // ... var washingtonRef = db.collection('cities').doc('DC');  // Atomically add a new region to the "regions" array field. var arrUnion = washingtonRef.update({   regions: admin.firestore.FieldValue.arrayUnion('greater_virginia') }); // Atomically remove a region from the "regions" array field. var arrRm = washingtonRef.update({   regions: admin.firestore.FieldValue.arrayRemove('east_coast') }); 
like image 51
Sean Blahovici Avatar answered Oct 03 '22 05:10

Sean Blahovici


Firestore currently does not allow you to update the individual fields of an array. You can, however, replace the entire contents of an array as such:

admin.firestore().doc(`users/${userA}/chats`).update('array', [...]); 

Note that this might override some writes from another client. You can use transactions to lock on the document before you perform the update.

admin.firestore().runTransaction(transaction => {   return transaction.get(docRef).then(snapshot => {     const largerArray = snapshot.get('array');     largerArray.push('newfield');     transaction.update(docRef, 'array', largerArray);   }); }); 
like image 39
Sebastian Schmidt Avatar answered Oct 03 '22 03:10

Sebastian Schmidt