Home > database >  How to get data from one firestore collection to another?
How to get data from one firestore collection to another?

Time:01-31

I would like to know How I can fetch all documents from the "playgrounds" collection that are associated with a specific document in the "solutions" collection in my React app

I have the following collections:

"users": This collection contains user documents.
"solutions: This collection contains solution documents.
"playgrounds": This collection contains documents for different solutions in different languages. For example, a user submitted a solution in 2 different languages, such as React and Vue, so I'll create two documents in the playgrounds collection to store those solutions.

How can I fetch those two solutions in the corresponding solution document?

Please help me with that!

CodePudding user response:

You can get the High-level overview of your database like below as per the Provided inputs

Store Solutions in the Playgrounds collections as a sub-collection of its documents

Playgrounds(Collection)                       Users(Collection)
├──Document(Playground)                       ├──Document
|      └──pid                                 |  └──uid
|      └──Solutions(sub-collection)           ├──Document
|         ├──Document(Solution)               |  └──uid
|         |  └──sid
|         ├──Document(Solution)
|            └──sid 

Now to get a solutions of a particular Playground we just have to get the corresponding subcollection

Let’s say You are in Playground A and you need to get all solutions which is posted for Playground A you will do something like :

import { collection, getDocs } from "firebase/firestore";

const fetchSolutions = async (playgroundId = "A") => {
  const playgroundRef = collection(db, "playgrounds", playgroundId, "solutions");
  const solutions = await getDocs(playgroundRef);

  solutions.forEach((solution) => {
    console.log(solution.id, " => ", solution.data());
  });
};

For more information go through this docs and this doc

  • Related