I am using cloud firestore database to store documents for user inside a next.js application, the collection path is as follows
collection "userDocs"
└─ document "userEmail"
└─ collection "docs"
└─ document "documentObject"
I was using Firebase v9 SDK and I downgraded to firebase v8 and I am still facing the same issue.
This code snippet is where I add a new document to the database which is done and reflects successfully in the Firebase console
db.collection("userDocs").doc(session.user.email).collection("docs").add({
fileName: input,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
When trying to fetch documents from the database I tried the following approaches:
1. Using react-firebase-hooks
const [snapshot] = useCollectionOnce(
db
.collection("userDocs")
.doc(session?.user.email)
.collection("docs")
.orderBy("timestamp", "desc")
);
2. Using Firebase query
useEffect(() => {
var query = db.collection("userDocs");
query.get().then((querySnapshot) => {
querySnapshot.forEach((document) => {
document.ref
.collection("docs")
.get()
.then((querySnapshot) => {
console.log(querySnapshot);
});
});
});
});
This is how I tried to achieve it using 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())}`);
});
}, []);