Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase – collection.doc is not a function

I’m getting the following error when trying to update a document in my Firestore database.

Uncaught TypeError: machinesCollectionRef.doc is not a function

I’m reading the data just fine in another component of my React app, so I know it’s not an issue with accessing the db, just probably an issue with my understanding of the documentation. Can anyone let me know where I’m going wrong?

import React, { useState } from 'react'
import {db} from'../firebase'
import {collection} from 'firebase/firestore'

export const UpdateMachine = ({machine}) => {
  const [name, setName] = useState(machine.name)

  const onUpdate = () => {
      const machinesCollectionRef = collection(db, "Regions/Alberta/Machines")
      machinesCollectionRef.doc(machine.id).update({...machine, name})
  }

  return (
      <>
        <input value={name} onChange={(e) => {setName(e.target.value)}}/>
        <button onClick={onUpdate}>Update</button>
      </>
  )
}

EDIT: This is where I’m defining db

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import firebase from 'firebase/compat/app'
import "firebase/compat/auth"
import {getFirestore} from '@firebase/firestore'

const app = firebase.initializeApp({
    apiKey: "AIzaSyBhoMyfDx98mIrm_brf1Zm0MZTs7tjUTUA",
    authDomain: "erg-app-dev.firebaseapp.com",
    projectId: "erg-app-dev",
    storageBucket: "erg-app-dev.appspot.com",
    messagingSenderId: "389918287574",
    appId: "1:389918287574:web:a53db3a285a8540b094b77"
})


export const db = getFirestore(app)
export const auth = app.auth()
export default app

>Solution :

Since you’re using the new modular API doc is now a top-level function, rather than a method on a collection. The same applies to updateDoc. So:

import {collection, doc, updateDoc} from 'firebase/firestore'

export const UpdateMachine = ({machine}) => {
  const [name, setName] = useState(machine.name)

  const onUpdate = () => {
      const machinesCollectionRef = collection(db, "Regions/Alberta/Machines")
      updateDoc(doc(machinesCollectionRef, machine.id), {...machine, name});
  }
  ...

I recommend keeping the following Firebase documentation handy:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading