"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?

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

Organizing and managing one-on-one table tennis matches using a customized data structure. Leveraging the power of Vue, JavaScript, and

Seeking advice on the best approach for storing table tennis match data in a web application. I currently have a method in place that works, but I'm open to suggestions for improvement. Here is my current idea: matches: [ { id: 1 datePlayed ...

The Angular application shell build has produced two new folders within the dist directory. I'm curious about their purpose and how they can

Whenever I execute the ng run my-app:app-shell -c production command, it creates 2 folders within the dist directory - one for the browser and one for the server. Now, I find myself with 2 different commands to use: npm build --prod (for a regular build) ...

Despite the presence of the element, ngIf fails to render it on the screen

{{ element.number }} <div *ngIf="element.number"> 123 </div> Even though the server is sending the number, it's not displaying 123 as expected. Tried updating the ngIf to: *ngIf="element?.number" What could ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

Intercepting HTTP requests in Angular, but not making any changes to the

Working on Angular 13, I am trying to attach a JWT token to the headers in order to access a restricted route on the backend. However, after inspecting the backend, it seems that the JwtInterceptor is not modifying the HTTP request headers. I have included ...

Issue occurred while trying to deploy Firebase functions following GTS initialization

Objective: I am aiming to integrate Google's TypeScript style guide, gts, into my Firebase Functions project. Desired Outcome: I expect that executing the command firebase deploy --only functions will successfully deploy my functions even after init ...

Converting Promises to Observables

Struggling with the syntax as I delve into learning Angular, I need to transform a promise into an Observable. Let me share what I've encountered: In the function getCountries (subscribed by another utility), there is a call required to fetch a list ...

conducting thorough analysis for detecting modifications akin to $watchCollection in Angular2

I have a situation where I am passing an array of objects from my parent component to child components. Even when a new item is added to the array or the property of an existing object changes, it fails to trigger the ngOnChanges for the affected component ...

Ionic 4: Facing issues with setting complete background image on ion-card

https://i.stack.imgur.com/3lH6h.png I'm currently attempting to set a background image for an Ion-card in order to completely cover the card's area. However, I'm facing an issue where the background image does not cover the entire area and ...

Enhancing current interfaces

I'm exploring Koa and the module system in Node.js. Although I'm not asking about a specific koa question, all the code I'm working with involves using koa. In Koa, every request is defined by the Request interface: declare module "koa" { ...

Having trouble getting Laravel and Angular to filter data by categories?

I am currently developing an ecommerce project using Laravel and Angular. I have products and brands associated with these products. In my function to retrieve the products in Laravel, I have used a nullable parameter like this: public function index($bran ...

Issue with primeNg password ToggleMask functionality not functioning properly

While working on my code, I successfully implemented the passwordModule. However, when I attempted to add toggle mask functionality, I encountered an issue. <input id="float-password" type="password" [to ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

How to Share Angular Modules Between Two Projects with Ivy Compilation Necessity

Query: I am faced with the challenge of sharing common modules between two Angular projects, one of which requires full Ivy compilation to function properly. To manage these shared resources, we have set up a private GitHub NPM repository. However, becaus ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

Tips for transferring data from an Angular @Input property to another variable and displaying it in a child component

I am dealing with the following parent HTML structure: <p>Parent</p> <app-child [mainData]="mainData"></app-child> In parent.ts, I have the following code: mainData = []; ngOnInit() { this.myService((res)=>{ this.mainData = ...

Tips for bringing in Cassandra driver types in TypeScript?

In the documentation for the Cassandra driver, they provide code examples like this: const Uuid = require('cassandra-driver').types.Uuid; const id = Uuid.random(); However, when attempting to use this in Visual Studio Code, the Uuid class type ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

What strategies should be employed when creating e2e tests that require a specific order of execution?

In the process of developing e2e tests for our angular app using Cypress.io, we are encountering a challenge. While we understand that tests should ideally not rely on each other, it seems challenging to avoid in a practical application. Consider a user ne ...