Firestore Add value to array field

Kravitz picture Kravitz · Jan 12, 2018 · Viewed 34.1k times · Source

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.

Answer

Sean Blahovici picture Sean Blahovici · Sep 28, 2018

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

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