2

This is my first time asking a question on here, usually I can find what I'm looking for, but I am upgrading from Firebase 8 to Firebase 9 in an ionic/react FC app, and have got some of it figured out, but I cannot figure out how to get a single document from nested collections. In Firebase 8 it would look like:

db.collection('department').doc(deptId).collection('employees').doc(empId).get()...

I have tried a couple ways with collectionGroup, and don't get anything returned at all, but I'm not even sure that is the correct way to go. Any help would be greatly appreciated!! Thanks!

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

1 Answers1

4

If you already know syntax (and how Firebase works) of Firebase JS SDK (V8 and before), I'll highly recommend checking out the documentation as they have syntax of both side by side. Just click on the modular tab in documentation. Fetching a single document will be as shown below:

import { doc, getDoc } from "firebase/firestore";

const docRef = doc(db, "department", deptId, "employees", empId);
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  console.log("No such document!");
}

Also checkout: Firestore: What's the pattern for adding new data in Web v9?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Oh my god, I feel like such an idiot now! I can't tell you how many times I tried that exact same code, but never checked the existing code before it. It was never even making it to that query. Some code I have right before that to set some global state was not working so it was not even getting to the query. My apologies, but thank you so much for taking the time to answer my question Dharmaraj, at least I knew then I was on the right track initially, I really appreciate it!! Hopefully this will help out others as well. – toddinator2 Jan 06 '22 at 20:22