Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Subcollection inside a Collection in Firestore Web Version 9 (Modular)?

I was using the chaining mode of the Firestore Web 8, but I'm in the way of updated it to Module 9 and have been a hard time trying to figure out how to get all the content of my subcollection (collection inside my collection).
My older function is like this and works fine:

function getInfo(doc_name) {
    let infoDB = db
      .collection("collection_name")
      .doc(doc_name)
      .collection("subcollection_name")
      .get();

    return alunoHistorico;
  }

so with the module way I tried this code

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

const docRef = doc(db, "collection_name", "doc_name");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  // doc.data() will be undefined in this case
  console.log("No such document!");
}

but the function doc() expects a even arguments (not counting the db argument) so if I try to use with 3 arguments like this, I get a error:

const docRef = doc(db, "collection_name", "doc_name", "subcollection_name");

to it work I have to pass the exactly document that is inside the subcollection

const docRef = doc(db, "collection_name", "doc_name", "subcollection_name", "sub_doc");

but it doesn't work for me because I have a list os docs inside the subcollection, that I want o retrieve. So how can I get all my docs inside my subcollection?

Thanks to anyone who take the time.

like image 614
Kleber Germano Avatar asked Sep 22 '21 15:09

Kleber Germano


People also ask

How do I create a Subcollection in firestore v9?

Firestore doesn't have operations for creating collections and subcollections. You just start writing documents to them, and they will appear in the console. Are you actually asking how to write a document to a subcollection, regardless of whether or not that's previously been done?

How do I get specific data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

What are FireStore sub-collections and how do they work?

I’d like to talk at a high level about Firestore sub-collections. First, we need to review the Firestore data model. Firestore is a document/collection database. Documents hold whatever JSON data you’d like, but they must live within a collection. A document can have any number of sub-collections with their own documents.

How do I see orphaned collections in FireStore?

You can see these orphaned sub-collections by clicking through the Firestore web console. But you have to click through every single document to find them, because orphaned sub-collections don’t show up when you query their parents. This is garbage.

How is data stored in Cloud Firestore?

As detailed in the Cloud Firestore documentation, data in Firestore is stored into documents, which are “organized into collections”. Documents can contain subcollections which, in turn, can contains documents. The documentation also indicates that:

What is the FireStore data model?

First, we need to review the Firestore data model. Firestore is a document/collection database. Documents hold whatever JSON data you’d like, but they must live within a collection. A document can have any number of sub-collections with their own documents. And you can keep nesting your data within sub-collections to your heart’s content.


Video Answer


2 Answers

You need to use collection() to get a CollectionReference instead of doc() which returns a DocumentReference:

const subColRef = collection(db, "collection_name", "doc_name", "subcollection_name");
// odd number of path segments to get a CollectionReference

// equivalent to:
// .collection("collection_name/doc_name/subcollection_name") in v8

// use getDocs() instead of getDoc() to fetch the collection

const qSnap = getDocs(subColRef)
console.log(qSnap.docs.map(d => ({id: d.id, ...d.data()})))

I wrote a detailed answer on difference between doc() and collection() (in V8 and V9) here:

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

like image 130
Dharmaraj Avatar answered Oct 14 '22 03:10

Dharmaraj


If someone want to get realtime updates of docs inside sub collection using onSnapshot in Modular Firebase V9, you can achieve this like:

import { db } from "./firebase";
import { onSnapshot, collection } from "@firebase/firestore";

let collectionRef = collection(db, "main_collection_id", "doc_id", "sub_collection_id");

  onSnapshot(collectionRef, (querySnapshot) => {
    querySnapshot.forEach((doc) => {
      console.log("Id: ", doc.id, "Data: ", doc.data());
    });
  });
like image 5
Azhar Zaman Avatar answered Oct 14 '22 01:10

Azhar Zaman