How do I access the top-level collection within a list of documents in Firestore?

In example1, I have a structure where there are collections followed by documents in a sequence like collection - doc - collection - doc - collection.

Conversely, in example2, there is just a single collection mentioned.

In example1's structure, I am able to import all document lists from the last collection. However, in example2's structure, I'm unable to retrieve document lists from the collection.

How can I access the top-level collection within the document lists?

Below is the code implementation:

// This is example1 and it works successfully!!
  dbService
    .collection("users")
    .doc(uid)
    .collection(uid)
    .doc("video")
    .collection(uid)
    .onSnapshot((snapshot) => {
      snapshot.docs.map((doc, index) => {
        videoList.push(doc.data());
        console.log(doc.data());
      });
    });



// This is example2 but unfortunately, it doesn't work properly.
  dbService
   .collection("users")
   .onSnapshot((snapshot) => {
    snapshot.docs.map((doc, index) => {
      videoList.push(doc.data());
      console.log(doc.data());
    });
  });

Example2 returns an empty array. Any ideas on why this might be happening?

Answer №1

Retrieving data from Firestore is done in a shallow manner. This means that when you fetch documents from the users collection, no data from subcollections is automatically retrieved.


If you need to retrieve data from a specific user's video subcollection, you will have to make an additional call:

  dbService
   .collection("users")
   .onSnapshot((snapshot) => {
    snapshot.docs.map((doc, index) => {
      if (/* this is a user you are interested in */) {
        snapshot.ref.collection(videos).get().then((videos) => {
          videos.forEach((video) => {
            videoList.push(video.data());
          })
          console.log(doc.data());
        });
      }
    });
  });

If you want to retrieve all videos for all users, you can utilize a collection group query:

  dbService
   .collectionGroup("videos")
   .onSnapshot((snapshot) => {
    snapshot.docs.map((doc, index) => {
      videoList.push(doc.data());
      console.log(doc.data());
    });
  });

To find the ID of the user for a specific video within this context, you can identify it using doc.ref.parent.parent.id.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform an object into an array using JavaScript with the help of Lodash, Azure Functions, and Azure Logic Apps

To achieve the desired result of extracting JSON from a proprietary content management system, transforming it into a CSV, and depositing that CSV in an Office 365 shared drive, a combination of Azure Function and Azure Logic App is utilized. The Node/Java ...

Activate a function when clicking on a Bootstrap toggle switch (checkbox)

Is it possible to have the function updateText() executed when I click on the checkbox with the id text_mode? I attempted using onClick="updateText()", but it didn't yield the desired outcome. While searching for solutions, I noticed that many respons ...

Performing Jquery functions on several elements at once

Looking at the code snippet below, there are two buttons and an input in each container. The input calculates and adds up the number of clicks on the 2 buttons within the same container. However, it currently only works for the first container. How can thi ...

What could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

Focus is lost on React input after typing the initial character

Whenever I input text, the focus is lost. All my other components are working fine except this one. Any ideas why this might be happening? I attempted to create separate components and render them in my switch statement, but it still doesn't work. O ...

Nuxt encountered an issue with Vue hydration: "Tried to hydrate existing markup, but the container is empty. Resorting to full mount instead."

I'm facing an issue while trying to integrate SSR into my project. I keep encountering this error/warning. How can I pinpoint the problem in my code? There are numerous components in my project, so I'm unsure if I should share all of my code, b ...

What is the best way to update React State after making an asynchronous call to MongoDB?

I have been facing a common issue, but couldn't find an up-to-date solution on Stack Overflow specifically for React/Meteor. My goal is to query a mongoDB to retrieve data and then pass it into the state of my React components. Currently, I am queryin ...

Issues rendering ThreeJS geometry data imported from Json file

Having been a dedicated user of this website for some time now, I must admit that this is the first instance where I find myself in need of posting a question. The issue at hand revolves around a Json file from which I extract data and manipulate it with m ...

Extracting data from a JSON array using JavaScript: A guide

I'm encountering an issue with a PHP function that returns an array to JavaScript. Here's how the code looks: $data['first'] = 10; $data['second'] = 20; echo json_encode($data); Upon receiving the value in JavaS ...

Error in HTML: Text variable is not displaying the number value

Currently, I am facing a challenge with my code. I have a variable named "Timer" that I want to increment by one and then display the number. However, I am unable to see the "Test Successful!" message displayed on the screen. Surprisingly, there are no e ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

A guide on adding meta description in Sails JS version 1.0

Wondering how to add a meta description tag in a Sails JS version 1.0 application to improve SEO? Despite having a web app, Google's indexing isn't displaying the right information I want. The descriptions shown under the links are not clear eno ...

Comparison between PHP's JSON parser and Javascript's JSON parser

Can anyone help me with this PHP serialize JSON encoding issue? json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))')); // output json: {"pattern":"^(?:\/?site ...

What is the process to extract the displayed font using JavaScript?

One interesting feature of Google Chrome is that it displays the rendered font in DevTools. For instance, when you have the CSS code: font-family: Montserrat, Helvetica, sans-serif; and the Montserrat font is not available or disabled, Chrome will indic ...

Changing a JavaScript string into an array

I have extracted an array of objects from a hidden HTML input field and received the following string: "{"id":"1234","name":"john smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0a9b7b3aeb29ab8b6bbb2f4b9b5b7" ...

Oops! It seems like there is an issue with reading the property 'filter' of an undefined object. Any ideas on how to resolve this error

Having an issue with a custom filter that is causing an error "ERROR TypeError: Cannot read property 'filter' of undefined". I need help fixing this as it's preventing anything from rendering on the page. Any suggestions on what changes I sh ...

What is the proper way to install Vuetify when the webpack.config.js file is missing?

The Vuetify documentation mentions the following: After installation, you need to locate your webpack.config.js file and insert the provided code snippet into the rules array. If you already have a sass rule configured, you may need to make some adjustme ...

How can I generate an HTML table by making JavaScript AJAX requests in a structured manner?

I'm new to JavaScript and currently working on dynamically creating a table. I've encountered an issue with the order of execution in my code. I understand that JavaScript doesn't execute sequentially, so I'm looking for a workaround. ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

How to implement Ajax to immediately display the first comment created on a webpage

Currently, my application can add comments to microposts that already have existing comments. Here is the simplified version of _micropost.html.erb: <li id="micropost-<%= micropost.id %>"> <span class="content"> <%= micropost.co ...