我试图在我的项目模式中创建一个“AddFolderButton”,所以我想要的是添加后我单击按钮,它应该更新 firebase 云中的名称和 userId。 但它显示错误为: 将文件夹添加到 Firestore 时出错:无法使用空路径调用函数 collection()。
下面是我的 firebase.js
import firebase from "firebase/compat/app"
import "firebase/compat/auth"
import { getFirestore, collection, addDoc, serverTimestamp } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
const app = firebase.initializeApp({
//creds
})
export const db = getFirestore(app);
export const database = {
folders: collection(db, 'folders'),
files: collection(db, 'files'),
formatDoc: (doc) => ({ id: doc.id, ...doc.data() }),
getCurrentTimestamp: serverTimestamp(),
};
export const storage = getStorage(app);
export const auth = app.auth()
export default app
import React, { useState } from "react";
import { Button, Modal, Form } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFolderPlus } from "@fortawesome/free-solid-svg-icons";
import { database, db } from "../../firebase";
import { useAuth } from "../../contexts/AuthContext";
import {
getFirestore,
collection,
getDocs,
addDoc,
} from "firebase/firestore";
export default function AddFolderButton({ currentFolder }) {
const [open, setOpen] = useState(false);
const [name, setName] = useState("");
const { currentUser } = useAuth();
function openModal() {
setOpen(true);
}
function closeModal() {
setOpen(false);
}
async function handleSubmit(e) {
e.preventDefault();
try {
console.log("Database folders:", database.folders);
const folderRef = await addDoc(collection(database.folders), {
name: name,
userId: currentUser.uid,
createdAt: database.getCurrentTimestamp(),
});
console.log(folderRef.id);
setName("");
closeModal();
} catch (error) {
console.error("Error adding folder to Firestore:", error.message);
}
}
return (
<>
<Button onClick={openModal} variant="outline-success" size="sm">
<FontAwesomeIcon icon={faFolderPlus} />
</Button>
<Modal show={open} onHide={closeModal}>
<Form onSubmit={handleSubmit}>
<Modal.Body>
<Form.Group>
<Form.Label>Folder Name</Form.Label>
<Form.Control
type="text"
required
value={name}
onChange={(e) => setName(e.target.value)}
/>
</Form.Group>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={closeModal}>
Close
</Button>
<Button variant="success" type="submit">
Add Folder
</Button>
</Modal.Footer>
</Form>
</Modal>
</>
);
}
上面是我的AddFolderButton.js
起初 userId 在 firebase 中更新,但现在控制台输出相同的错误
如果您让我们知道错误来自哪个
collection()
,将会很有帮助。
也就是说,我怀疑它来自:
collection(database.folders)
因为
collection()
有 2 个参数,但您只提供了一个。您需要为其提供一个 Firestore
对象,通常是从 getFirestore()
获得的对象