"Exploring the method to navigate through a nested Firebase collection linked to its parent collection

I have a forum application in development where users can ask questions and receive answers, each answer having its own 'like' feature. I am trying to access the 'likes' subcollection when viewing an answer, but I am unsure of how to do so. After researching, I came across collection group queries in Firebase, but my knowledge is limited in this area. Can someone assist me in retrieving the 'likes' collection?

getComments(id) {
  this.commentCollection = this.questionCollection.doc(id).collection<Comment>('answer');
  this.comments = this.commentCollection
    .snapshotChanges()
    .pipe(map(changes =>{
      return changes.map(a=>{
        const data = a.payload.doc.data() as Question;
        data.id = a.payload.doc.id;
        return data;
      })
    }));
  return this.comments;
}

Here I am retrieving the comment collection.

<li *ngFor="let comment of selectedComment |async">
  <div class="comment-main-level">
    <div class="comment-box">
      <div class="comment-head">
        <span>{{comment.time.toDate() | date: 'dd MMM hh:mm'}}</span>
        <i>Likes</i>
        <i (click)="likePost(comment.userID,comment.id)" class="fa fa-thumbs-up"></i>
        <i (click)="editComment($event, comment)" *ngIf="comment.userID==authService.currentUserId" class="fa fa-pencil-alt">  </i>
        <i (click)="deleteComment(comment.id)" *ngIf="comment.userID==authService.currentUserId" class="fa fa-trash-alt"></i>
      </div>
      <div class="comment-content">
        {{comment.answerBody}}
      </div>

This is the HTML code for displaying comments. I want to include the like count for each comment within this section. How can I retrieve the like collection? https://i.sstatic.net/wF24E.jpg

Answer №1

In my perspective, you have the ability to approach this in a manner that mirrors how you retrieve the answer collection within the getcomment function. Accessing nested collections of documents can be done using the collection method and nested documents within a collection through the doc method. This process can continue until you reach the final level of your structure - following a pattern like this:

parentCollectionReference.doc(<docid>).collection(<nestedCollectionId>).doc(<nestedDocId>).collection(<collectionNestedInNestedDoc>).doc... and so on.

It's important to note that you will already have the document id of the answer selected by the user, let's call it anwserId. Since you are already accessing the answer collection in the getcomment function, assuming the reference is stored in this.commentcollection, the logic remains consistent with the getcomment method. The key difference lies in obtaining the correct subcollection reference. A theoretical representation of the code could look like this:

this.likeCollection = this.commentcollection.doc('anwserId').collection<Likes>('likes');

The remaining steps can follow a similar structure to that of the getcomment function.

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

Propositional Properties within the Interface

I have a question about interfaces: Currently, I am working on a dynamic component that needs to change based on the page it's on. The structure of my interface is as follows: interface Props { heading: string; description: string; signUp?: boolean; ...

Using custom Components to accept HTML input

I have recently developed a custom component to arrange content within IonCardContent. It has been effective for my current requirements: interface ContainerProps { position?: string; content?: string, colour?: string; custClass?: string; } ...

"Protractor's browser.wait in Angular application fails to wait for the element to be visible

I am encountering an issue with the wrong login message. I am using async spec along with browser.wait to wait for the element to appear in the DOM, but it is not functioning as expected. Instead of waiting for the specified timeout if the element is not p ...

Obtain information from a PHP file using AngularJS 2

Can you guide me on how to post data and receive a response from a PHP page in AngularJS 2? I want to send data from auth.js file to session.php for storing the session value. Please show me how to do this using HTTP POST method. retu ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

Change TypeScript React calculator button to a different type

I am currently troubleshooting my TypeScript conversion for this calculator application. I defined a type called ButtonProps, but I am uncertain about setting the handleClick or children to anything other than 'any'. Furthermore, ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

In TypeScript, is it possible to indicate that a function will explicitly define a variable?

In TypeScript, I am working on creating a class that delays the computation of its information until it is first requested, and then caches it for future use. The basic logic can be summarized as follows. let foo: string | undefined = undefined; function d ...

Angular generating JSON data

I am trying to figure out how to extract and display the short_title from the JSON object with the "id": 28. I want to use Angular to render this title within an HTML page. { "content": [ { "id": 29, "short_title": "Flow", ...

Tricks to access value from a Nativescript array of Switch elements when tapping a Button

Scenario: In my project, I am using Nativescript 5.0 with Angular. The data is fetched from an API and displayed in customers.component.ts I am successfully rendering the elements based on the received IDs in customers.component.html When the user inter ...

Utilize ngx-translate with an array as interpolation values

When working with ngx-translate, I use the instant method to translate messages into the user's language. These messages are provided as JSON objects and some of them contain dynamic values: { "message.key": "First value is {{0}} and se ...

How can we prevent new chips (primeng) from being added, but still allow them to be deleted in Angular 2?

Hey there! I'm currently exploring how to make the chips input non-editable. I am fetching data objects from one component and using the keys of those objects as labels for the chips. Check out my HTML code below: <div class="inputDiv" *ngFor="le ...

Designing functional components in React with personalized properties utilizing TypeScript and Material-UI

Looking for help on composing MyCustomButton with Button in Material-ui import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps { 'aria-label': string, // Adding aria-label as a required pro ...

Expressjs makes it easy to upload audio files to your website

Currently, I'm developing a music app and I'm looking for the best way to upload an audio file in my ExpressJS application. Is it possible to use Cloudinary or is there another method that is more efficient? I attempted to follow the same proces ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Send information to the main application component

Can data be passed two or more levels up from a Child Component to the App Component? https://i.stack.imgur.com/JMCBR.png ...

Typescript Server Problem: Critical Error - Mark-compacts Inefficiently Close to Heap Limit, Allocation Unsuccessful - JavaScript Heap Exhausted

Whenever I run my CRA project, I consistently encounter this error in my console. It seems to be related to the typescript server. Is there a solution for this issue? 99% done plugins webpack-hot-middlewarewebpack built preview 7c330f0bfd3e44c3a97b in 64 ...

What's the best way to import a file from OneDrive to an Angular app using Typescript?

I am currently working on an Angular application that utilizes OneDrive/Sharepoint for file storage. Authentication is functioning properly, and I can successfully save files. However, I am encountering an issue when attempting to download a file created a ...

The MSI installer for electron-builder is rejecting the asar file due to its excessive

My Angular application requires an MSI installer, but I encountered an error while trying to create one for the electron app I developed using `npm run electron`. The error message states: Error LGHT0263 : 'C:...\release\win-unpacked&bsol ...