SAIKAT
SAIKAT

Reputation: 113

How to fetch all documents from a firebase collection where each document has some sub collection and in sub collection there is a document?

I am making an Admin dashboard. I want to show all user's details and their orders. When I want to fetch all documents inside the user collection its returning empty. For more In user collection, each document has some sub-collection. In the account sub-collection, there is a document exists with name details where user account details are available as shown in snapshots.enter image description hereenter image description hereenter image description here My code is

export function getUsers() { 
  return firebase.firestore().collection("users").get();
}

Upvotes: 5

Views: 1478

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599946

Firestore queries only access a single collection, or all collections with a specific name. There is no way to query a collection based on values in another collection.

The most common options are:

  1. Query the parent collection first, then check the subcollection for each document. This approach works best if you have relatively few false positives in the parent collection.
  2. Query all child collections with a collection group query, then check the parent document for each result. This approach works best if you have relatively few false positive in your child collection query.
  3. Replicate the relevant information from the child documents into the parent document, and then query the parent collection based on that. For example, you could add a hasOrders field or an orderCount in the user document. This approach always gives optimal results while querying, but requires that you modify the code that writes the data to accommodate.

The third approach is typically the best for a scalable solution. If you come from a background in relation databases, this sort of data duplication may seen unnatural, but it is actually very common in NoSQL databases where you often have to change your data model to allow the queries your app needs.

To learn more about this, I recommend reading NoSQL data modeling and watching Getting to know Cloud Firestore.

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50930

If you store user's details directly in the document instead of 'account' sub-collection then fetching "users" collection will return all users' documents with their data. If you say there's no reason then I'd recommend doing this.

Other option would be to use collectionGroup query on "account" which will fetch all the documents from sub-collections named as "account" i.e. giving you every user's account details.

const snap = await db.collectionGroup('account').get()
const users = snap.docs.map(d => ({id: doc.ref.parent.parent.id, data: d.data()))

Here, id is user's document ID.

Upvotes: 1

Related Questions