node.js - Firestore Add value to array field

ID : 131329

viewed : 12

Tags : node.jsfirebasegoogle-cloud-functionsgoogle-cloud-firestorefirebase-adminnode.js

Top 4 Answer for node.js - Firestore Add value to array field

vote vote

92

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') }); 
vote vote

83

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);   }); }); 
vote vote

78

This is 2021 and after many updates of firebase firestore, the new method to add data in array without removing another data is

      var washingtonRef = db.collection("cities").doc("DC");        // Atomically add a new region to the "regions" array field.        washingtonRef.update({      regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")      });        // Atomically remove a region from the "regions" array field.     washingtonRef.update({         regions: firebase.firestore.FieldValue.arrayRemove("east_coast")       }); 
vote vote

63

Top 3 video Explaining node.js - Firestore Add value to array field

Related QUESTION?