Home > Back-end >  Firebase - collection.doc is not a function
Firebase - collection.doc is not a function

Time:04-18

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

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

CodePudding user response:

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:

  • Related