Retrieve all documents from a Firebase User's collection

Recently, I created a Firebase cloud function where my goal is to access every user's internal collection named 'numbers' and examine each document within that collection for some comparisons.

Do you have any insights on how I can achieve this?

Despite being new to Firebase, I am struggling with the database navigation commands as they are not sticking very well with me.

I have experimented with various commands but haven't had much success

const snapshot = functions.database.collection('users').collection('numbers').get()
 let sfRef = db.collection('users');
    sfRef.getCollections().then(collections => {
        collections.forEach(collection => {
        console.log('Found subcollection with id:', collection.id);
        });
    });

Below is a general outline of the cloud code structure

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

export const prize1 = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
    const users = functions.database.ref('/users/numbers')

    console.log("")
    return null;
});

While I believe I understand the concept, I am encountering difficulties with the syntax.

The process involves accessing the collection of users, iterating through each user document, going into the 'numbers' collection within each user, examining each document within the 'numbers' collection for logic/comparisons based on the numbers field.

Hopefully, these explanations shed light on my database organization.

Answer №1

If you want to retrieve data in this way, consider using the following code:

let usersRef = db.collection('users');
let allUsers = usersRef.get();
   .then(userSnapshot => {
     userSnapshot.forEach(userDoc => {
       userDoc.ref.collection('numbers').get().then(numSnapshot => {
         numSnapshot.forEach(numDoc => {
           console.log(numDoc.data().numbers);
           // Accessing numbers field of your numbers document
         });
       });
     });
   })
   .catch((error) => { 
       console.log("Error getting document: ", error);
   });  

To learn more about this process, reference here and here.

Answer №2

Instead of using functions to access the database, it is recommended to utilize them for creating triggers that respond to specific events. To retrieve data from Cloud Firestore, consider utilizing the Firebase Admin SDK through your admin credentials. Additionally, reviewing the official samples may provide valuable insights.

It's worth noting that there seems to be a mix-up in your code examples between accessing Cloud Firestore and Realtime Database, two distinct products. Given that your screenshot displays Firestore, focus on Firestore-specific APIs and disregard any references to Realtime Database.

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

How can jQuery incorporate additional selection criteria for a parent element?

How can I apply a specific criteria to a node that has been selected using jQuery? let objDIV = $("#selindividual").parent(); After retrieving the DIV, I want to target the following: button:contains(\"Submit\") If I had to do this in ...

HTML5 canvas game issue: background fails to load

I'm a beginner at designing games using HTML5 canvas. I've been following a tutorial on creating games in the style of Angry Birds from the 'pro html5 games' book. I've completed all the steps in the tutorial, but I'm facing a ...

What is the purpose behind enclosing a function expression in parentheses in JavaScript (apart from creating an IIFE)?

While delving into some advanced JavaScript concepts, I stumbled upon a piece of jQuery code on GitHub that caught my eye. It was an anonymous function wrapped in parentheses, which you can find here. Although I'm familiar with Immediately Invoked Fu ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

Perhaps dividing numbers with regular expressions

My HTML textarea allows users to input numeric serial numbers in various formats - either inline, separated by any character, or in columns from an Excel file. The serial codes are either 14 characters long if the first character is "1," or always 15 char ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is ...

Issue: Unable to find a compatible version of chokidar. Attempted chokidar@2 and chokidar@3 after updating npm to version 7.*.*

After using ejected CRA, it compiled successfully but then broke with the following error. The issue started to occur after updating npm from version 6 to 7. You can now view webrms in the browser. Local: http://localhost:3001 On Your Netw ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

What's the best way to incorporate necessary styles into text using particular fonts?

Is there a way to set letter spacing and word spacing for text on my website with the font 'classylight'? Adding classes to each post in the site map seems like a lengthy process. To save time, I attempted to use the attribute*=style property to ...

How to manipulate local JSON files using AngularJS

I recently started learning angularjs and have been spending hours online trying to figure out how to access data from a local json file without the need for hosting it on localhost. Unfortunately, I haven't come across any solutions yet. I attempted ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

The functionality of Javascript is being compromised when utilizing ng-repeat

Just recently diving into the world of AngularJs while developing a website. I've successfully retrieved data from Rest services on a page, and used ng-repeat to display it. The issue arises when I have a regular javascript element on the page that i ...

Receiving and transmitting messages repeatedly in Discord.JS

Currently, I am developing a simple bot. Interestingly, the bot seems to be responding multiple times to a single command. Here is the code snippet: const Discord = require('discord.js'); var bot = new Discord.Client(); const PREFIX = "+"; var ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...

What is the most efficient approach to save a value for future utilization in a subsequent function? I've heard that exploiting global variables is highly unfavorable

So I have this code that can be found at http://jsfiddle.net/8j947/10/. It returns either true or false for the variable isLive. My main concern now is how to utilize the variable onLive in a subsequent function. While I've encountered some solutions ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...