【问题标题】:Firebase Firestore db.collection is not a functionFirebase Firestore db.collection 不是函数
【发布时间】:2021-11-17 15:50:32
【问题描述】:

我正在开发一个轮班调度程序,我使用 firebase 身份验证和 firestore。我的想法是,当用户注册时,它会在集合“workers”中创建一个文档,并将文档 ID 设置为用户的电子邮件。当用户添加班次时,我想将班次信息添加到该用户文档内的子集合“班次”中,所有班次都将在其中存储。我已阅读并看过许多指南,但我无法正确理解语法/逻辑,并且由于语法的 firebase 更改,我包含了我使用的大部分设置。

firebase.js:

import { getAuth } from "firebase/auth";
import "firebase/firestore";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore"
require('firebase/auth');

const firebaseConfig = {
  ...
};
const app = initializeApp(firebaseConfig);

export const db = getFirestore(app);
export const auth = getAuth(app);
export default app

SignUp.js:

import { db } from "../firebase";
import { collection, addDoc, setDoc, doc } from "firebase/firestore";
import { useAuth } from '../contexts/AuthContext';
const { signup } = useAuth();  
 
    const handleSubmit = async (event) => {
    event.preventDefault();
    setError("");
      try{
        const data = new FormData(event.currentTarget);
        await signup ( data.get('email'), data.get('password'));
        const docRef = await setDoc(doc(db, "workers", data.get('email')), {
            firstName: data.get('firstName'),
            lastName: data.get('lastName'),
            email: data.get('email'),
            numberOfShifts: 0
        });
      }
      catch(e){
          console.error("Error adding document: ", e);
          setError("Failed to create an account");
      };

注册效果很好,文档 ID 是电子邮件。错误是当我尝试向该文档添加班次时(此阶段未创建班次集合)

Datasheed.js:(用户输入班次的地方)

import { auth } from "../firebase"
import { db } from "../firebase";

const commitChanges = async ({ added, changed, deleted }) => {
      if (added) {
        try {
          db.collection("workers")
          .doc(auth.currentUser.email)
          .collection("shifts")
          .add(added);
        } catch (e) {
          console.error("Error adding document: ", e);
        }
      }

现在我只是想添加,我得到的捕获的异常是: 添加文档时出错:TypeError: firebase__WEBPACK_IMPORTED_MODULE_5_.db.collection 不是函数。 从我读到的问题是我使用firebase模块化并且它不再有db.collection并且它使用集合引用。我是否也需要子集合的集合引用?为了实现这一点,我需要做哪些更改?

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    您正在使用模块化 SDK 以及 signup.js 中的模块化语法。您应该在其他任何地方使用相同的语法。尝试像这样重构:

    const commitChanges = async ({ added, changed, deleted }) => {
      if (added) {
        try {
          await addDoc(collection(db, "workers", auth.currentUser.email, "shifts"), added)
        } catch (e) {
          console.error("Error adding document: ", e);
        }
      }
    }
    

    您可以在documentation 中了解有关新语法的更多信息。

    【讨论】:

    • 非常感谢它有效,我现在明白我的错误了
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2021-10-31
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多