`Is there a way to retrieve the ID of a nested collection in Firestore using HTML?`

I've established a collection called "users" and within it, I have set up a subCollection named "innerGuides". While I know how to fetch data from the main collection "users", I'm curious about how to obtain the ID of my subCollection "innerGuides."

db.collection("users").doc(user.uid).collection("innerGuides").doc("BGP9O0Rh2ThiL40tXOVG").get().then(doc => {
    console.log(user.uid);
    console.log(doc.data().content);
  }).catch(error => {
    console.log(error);
  })

As you can observe, I am able to retrieve the UID of my main collection through "user.uid"; however, when it comes to the subCollection, how can I dynamically retrieve its UID? I manually entered the subCollection's UID, but I'm looking for a way to grab it automatically.

Answer №1

If you need to retrieve the identifier of a DocumentSnapshot, you can follow this example:

db.collection("users").doc(user.uid).collection("innerGuides").doc("BGP9O0Rh2ThiL40tXOVG").get().then(doc => {
    console.log(doc.id);  // <-- here
    console.log(doc.data().content);
  }).catch(error => {
    console.log(error);
  })

You may also check for doc.exists to verify if the document retrieved by get() actually exists.

To display your document along with its id, you could use something like this:

console.log({
  id: doc.id,
  ...doc.data(),
});

The id format for the sub-collection would be like:

users/the-user-id/innerGuides/BGP9O0Rh2ThiL40tXOVG
. It is not possible to directly extract only BGP9O0Rh2ThiL40tXOVG on its own as it requires the entire reference path for context. If you specifically need that value, you can parse it out from the id using JavaScript methods such as split():

const subId = id.split('/')[3]

It's advisable to validate the array prior to extraction, but this method should successfully fetch the id for you.

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 I find a user's ID in a JSON file using for...in loop in Discord.js?

I'm facing an issue with this loop where I am only able to retrieve the guild id instead of the user id that I actually need. Here is my code: for(let userID in money){ res.push({"guildid": message.guild.id, "id": userID, " ...

Would it be better to lock a variable stored in req.session, or opt for a massive global variable instead?

As I delve into creating a game using node.js, the premise is sending units on missions and waiting for their return. The challenge lies in ensuring that the same unit cannot be sent on two different missions simultaneously, nor can two sets of units be di ...

Developing a proxy that routes traffic through the user's device

I have developed a user interface for an API service that has limitations on the number of requests that can be made per machine within a specified time frame. Since I will be making API requests on behalf of multiple users, I am concerned about hitting t ...

The issue of HandleSubmit not functioning properly when used in conjunction with vee-validate on Vue3 and V

I am facing an issue with submitting a registration form that uses vee-validator for data validation. The handleSubmit function from vee-validator seems to be not returning or logging anything. Here is my code: <script setup lang="ts"> imp ...

Highcharts: Limiting the yAxis values to a maximum of two decimal places

Here is the code for my graph, which retrieves data from a PHP page and adds some series: $('#grafico_1').highcharts({ chart: { type: 'line', zoomType: 'xy', animation : false, events: { selection: functi ...

The Elusive Solution: Why jQuery's .css() Method Fails

I am currently facing an issue with my code that utilizes the jQuery .css() method to modify the style of a specific DIV. Unfortunately, this approach does not work as expected. To illustrate the problem, I have provided a simplified version of my code bel ...

What is the best way to eliminate an object from an array of objects that fulfills a specific condition?

Upon receiving an object in my function containing the information below: { "name": "Grand modèle", "description": "Par 10", "price": 0, "functional_id": "grand_modele_par_10", "quantity": 2, "amount": 0 } I must scan the next array of objec ...

Using a single function to generate multiple instances of a table in JavaScript

My journey to learning javascript led me to create a simple game called circle of crosses. Below is the code I used: (JS) // JavaScript code here (HTML) <!DOCTYPE html> <html> // HTML code here </html> I came across an issue whil ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

Adjust the height of an iframe dynamically according to the content within using JQUERY/Javascript

My current project involves loading an aspx web page within an iframe. The issue I am facing is that the content inside the iframe can sometimes exceed the height of the iframe itself, resulting in undesired scroll bars. To tackle this problem, I've ...

Mistaken data retrieved from a knockout observable array

My current project involves developing a web application using Asp.Net Mvc, where I am utilizing knockout Js to retrieve and send data to the Html View after manipulating the data. For instance, let's consider the data in an array called datainput: ...

What is the best way to remove an element within another element using Jquery?

$(document).ready(function() { $("#movieForm").submit(function(e) { e.preventDefault(); var wordToSearch = $("#movieInput").val(); $.ajax({ url: 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=x78wnu3hc3ve7amqef ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

When attempting a POST request to the API for a JavaScript application, a 400 Bad Request error is received, unlike with an ASP

Insightful discussion about CORS No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API I designed a local asp.net MVC application using C# (httpclient) for POSTing data to an API on ...

How to efficiently use nested $.each() in DataTables with jQuery

After receiving Json data from the server, I utilize DataTables to display the information accordingly. The json contains multidimensional arrays with rows consisting of columns that may have more than one value. Here's an excerpt: { "info_table ...

Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array. Below is the service where I am retrieving data from Firebase: File name: subcategory.service.ts export class SubcategoryService { subcategoryRef: Angula ...

The CSS theme toggler for Bootstrap

I am currently working on integrating a style switcher following the instructions provided at . However, when I add a title="" attribute to the CSS link, the CSS file fails to load on the page and the styles revert back to default Bootstrap. I have added ...

Building a new Vue.JS component inside of an existing parent component

Trying to create a nested component in VueJS has been a bit challenging for me. I have attempted something like this, but unfortunately, it doesn't seem to work as expected (the child component does not display anything): I am interested in exploring ...

Tips for optimizing performance in Vue.js data tables when working with large datasets stored in GCP Firestore

Having watched numerous videos on managing large amounts of data in GCP Firestore, I find myself wondering what the best approach is for working with a huge amount of data from Firestore. For example, if I have 800,000 products, how can I efficiently disp ...

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...