我正在使用 cloud firestore 資料庫在 next.js 應用程式中為用戶存盤檔案,收集路徑如下集合“userDocs”-> 檔案“userEmail”-> 集合“docs”-> 檔案“documentObject”。
我使用的是 firebase v9 sdk 并降級到 firebase v8,但我仍然面臨同樣的問題。
此代碼片段是我向資料庫添加新檔案的地方,該檔案已完成并在 firebase 控制臺中成功反映
db.collection("userDocs").doc(session.user.email).collection("docs").add({
fileName: input,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
嘗試從資料庫中獲取檔案時,我嘗試了以下方法
1- 使用 react-firebase-hooks
const [snapshot] = useCollectionOnce(
db
.collection("userDocs")
.doc(session?.user.email)
.collection("docs")
.orderBy("timestamp", "desc")
);
2-使用firebase查詢
useEffect(() => {
var query = db.collection("userDocs");
query.get().then((querySnapshot) => {
querySnapshot.forEach((document) => {
document.ref
.collection("docs")
.get()
.then((querySnapshot) => {
console.log(querySnapshot);
});
});
});
這就是我嘗試使用 firebase v9 實作它的方式
import {
collection,
query,
orderBy,
serverTimestamp,
setDoc,
doc,
collectionGroup,
onSnapshot,
getDocs,
} from "firebase/firestore";
useEffect(async () => {
const docRef = query(
collection(db, "UserDocs", session?.user.email, "Docs"),
orderBy("timestamp", "desc")
);
const docSnap = await getDocs(docRef);
const allDocs = docSnap.forEach((doc) => {
console.log(`Document ${doc.id} contains ${JSON.stringify(doc.data())}`);
});
}, []);
uj5u.com熱心網友回復:
我設法使用以下方法解決了這個問題:
1- 我重組了我的資料庫以包含“docs”集合,該集合包含在具有以下屬性 {email、fileName、timestamp} 的檔案物件中,而不是創建子集合。
我創建了以下方法來獲取資料并將其映射到狀態陣列中以便能夠呈現它
const getDocuments = async () => {
await db
.collection("docs")
.where("email", "==", session?.user.email)
.orderBy("timestamp", "desc")
.get()
.then((res) => {
setUserDocs(res.docs);
})
.catch((error) => {
console.log(error);
});
};
我仍然不太確定為什么這次嘗試比所有其他試驗都有效,但到目前為止我設法使事情有效,所以這是目前最重要的事情。
uj5u.com熱心網友回復:
問題是您沒有正確構建資料。如Firebase官方檔案中所示選擇一種資料結構,
當您在 Cloud Firestore 中構建資料時,您有幾個不同的選擇:
- 檔案
- 多個集合
- 檔案中的子集合
考慮每個選項的優勢,因為它們與您的用例相關
因此,根據您在答案中共享的代碼,您使用的結構是檔案中的嵌套資料。
我對你的第一種方法有點迷茫,但既然你終于讓它作業了,建議是根據檔案中的說明和適合你的需要來構建你的資料。
也可以看看
- https://firebase.google.com/docs/firestore
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395208.html
標籤:javascript 反应 火力基地 谷歌云firestore 下一个.js
