Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use arrayUnion with AngularFirestore?

I have a basic database that essentially stores an array of product id's underneath a user. The user can select products to add to the array so it makes sense to use 'arrayUnion' so I avoid reading and re-writing the array constantly, however, I keep getting the error *"Property 'firestore' does not exist on type 'FirebaseNamespace'."

I've followed the documentation found at: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array but I fear I'm still using it incorrectly.

My code for updating the array is:

 addToPad(notepadName: string){
    const updateRef = this.db.collection('users').doc(this.activeUserID).collection('notepads').doc(notepadName);
    updateRef.update({
      products: firebase.firestore.FieldValue.arrayUnion(this.productId)
    });
  }
like image 849
PeterL1995 Avatar asked Dec 20 '19 17:12

PeterL1995


2 Answers

First you need to import firestore:

import { firestore } from 'firebase/app';

Then you will be able to use arrayUnion:

addToPad(notepadName: string){
    const updateRef = this.db.collection('users').doc(this.activeUserID).collection('notepads').doc(notepadName);
    updateRef.update({
      products: firestore.FieldValue.arrayUnion(this.productId)
    });
  }
like image 132
Peter Haddad Avatar answered Sep 23 '22 01:09

Peter Haddad


import { arrayUnion } from '@angular/fire/firestore'

const path = `ai/${videoId}/panel-operation/${id}`
const myDoc: AngularFirestoreDocument<any> = this.afs.doc<any>(path)

const promise: Promise<void> = myDoc.update({ auxPanelSelections: arrayUnion({auxPanel: 'clip', operation: 'replace'}) }).catch((err: any) => {
  console.error(`oopsie - ${err.message}`)
  return null
})

auxPanelSelections is an array within the myDoc document

Note that the above code also works perfectly fine with arrayRemove

I cannot find the @angular/fire docs for arrayUnion but the generic docs are here

like image 27
danday74 Avatar answered Sep 19 '22 01:09

danday74