0

I’m a beginner in using Firebase’s Firestore database and I want to get feedback and input on the way I’m trying to implement a simple fetch & display.

Let’s say I have a collection of documents that represent each unit in a course that I want to render on the /courses page.

Unit 1
{
    unitName: "Unit 1"
    unitDesc: "this is description"
    // info below is not needed in homepage
    unitInfo: "asdfasdf"
    unitImage: "https://image.com"
    unitTags: ["tag1","tag2"]
}

Unit 2
{
    unitName: "Unit 1"
    unitDesc: "this is description"
    // info below is not needed in homepage
    unitInfo: "asdfasdf"
    unitImage: "https://image.com"
    unitTags: ["tag1","tag2"]
}

This is how I vision my project to work.

  1. /courses page: fetch and render a list of units that show unitName field unitDesc field. Notice how I do not need to fetch other fields to render this page, but I still need to because I will be accessing the entire document for every unit in the collection
  2. You click the unit button and it will redirect you to /courses/unit1 page. I am not sure if there’s a way to ‘bring’ information from the initial fetched data through the redirect process into a different URL (other than fetching info again on redirected URL)
  3. /courses/unit1 page: you see unit information on unitInfo, unitImage, and unitTags. I plan to fetch the single unit document again to render on this page.

I have a basic idea of how to implement this, but I feel there is a much better and more efficient way to achieve this. My current logic has flaws:

  1. when I wish to render the list of units via fetching collection, I need to fetch every single field even if I don’t need them.
  2. I need to fetch a single unit document once again when I’m redirected to /courses/unit-n

I’m asking for any kind of input and/or feedback on my approach, and if there’s a better simpler way to achieve this! Thanks a lot :)

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Tyler Kim
  • 181
  • 1
  • 11

1 Answers1

1

#1. When you perform a query in Firestore, you always get complete documents. Unfortunately, there is no way you can only get some fields of the document with the client-side SDK. It's the entire document or nothing. If you only need to get two fields out of 5 for example, then you should create another collection and store documents that only contain those two fields. This practice is called denormalization, and it's quite common practice when it comes to NoSQL databases like Firestore.

#2, #3. Since the ID of the document is actually the unit name, then you can add that to the URL and perform another request in the second screen to get the entire document from the first collection, the one that contains documents with all 5 fields.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193