Firebase - collection.doc 不是一个函数
2022-04-17
983
尝试更新 Firestore 数据库中的文档时出现以下错误。
Uncaught TypeError: machinesCollectionRef.doc is not a function
我在 React 应用程序的另一个组件中读取数据时一切正常,所以我知道这不是访问数据库的问题,可能是我对文档的理解有问题。有人能告诉我我错在哪里吗?
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>
</>
)
}
编辑:这是我定义数据库的地方
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
1个回答
由于您使用的是新的模块化 API,
doc
现在是顶级函数,而不是集合上的方法。这同样适用于
updateDoc
。因此:
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});
}
...
我建议随时查看以下 Firebase 文档:
Frank van Puffelen
2022-04-17