Firestore - how to add/subtract from a map of values

rhysclay picture rhysclay · May 10, 2018 · Viewed 10.8k times · Source

I am following the Firestore instructions for storing arrays: https://firebase.google.com/docs/firestore/solutions/arrays

Now what I would like to do is push to this map. For example right now i have:

Contacts
   contact1: true

But I would like to add or remove a contact for example:

Contacts
   contact1: true
   contact2: true

I have tried getting the Contacts map and using the push method but I don't think this will work as it is not a traditional array. For example:

this.afs
  .doc(`groups/${group.id}`)
  .ref.get()
  .then(doc => {
    let contacts: Array<any> = doc.data().contacts;

    contacts.push({ // error here as push is not a function
      [contactId]: true
    });

    console.log(contacts);
  });

Is there an easier way to do this - am I missing something?

Answer

voomin kim picture voomin kim · Dec 14, 2018

Simply push in map

use update() as following

const db = firebase.firestore();
const collection = db.collection('collectionId');

collection.doc(`groups/${group.id}`).update({

      "Contacts.contact3":true

    }).then(function(){

       console.log("Successfully updated!");

});