Itika Bandta
Itika Bandta

Reputation: 163

How to delete a document in a collection in Firebase/Firestore using its id?

I have a page in my application(in angular) where the user can post a comment. The comment is stored in Firestore collection with the name of "comments". The user should be able to delete the comment once he clicks the delete button next to it.

My comments.component.ts file code is as below -

import { Component, OnInit, Input} from '@angular/core';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

@Component({
selector: 'app-comments',
templateUrl: './comments.component.html',
styleUrls: ['./comments.component.css']
})
export class CommentsComponent implements OnInit {

comment : string;
allcomments : any[]=[];
@Input('postId') postId : string;
cid : any;

constructor() { }

ngOnInit(){

this.getComments();

}

postComment(){
firebase.firestore().collection("comments").add({
comment : this.comment,
post: this.postId,
owner: firebase.auth().currentUser.uid,
ownerName : firebase.auth().currentUser.displayName,
created: firebase.firestore.FieldValue.serverTimestamp()

}).then((data) =>{
 // console.log(data);
 this.getComments();
 console.log("commID",data.id);
 this.cid = data.id;

 }).catch((error)=>{
  console.log(error)
 })
}

getComments(){

this.allcomments = [];
firebase.firestore().collection("comments")
.where("post","==",this.postId)
.orderBy("created","desc")
.get().then((data)=>{

  data.docs.forEach((commentRef)=>{
  this.allcomments.push(commentRef.data())

  })

})
.catch((error)=>{
  console.log(error)
})

}

onDelete(){

 //console.log("INSIDE DELETE")
 console.log(this.cid)
 firebase.firestore().collection("comments").doc(this.cid).delete()
 .then(()=>{

  console.log("DELETED")
 }).catch((error)=>{
  console.log(error)
 });

}
}

The delete function takes cid as null. My question is, how can I pass the correct comment id of the comment I am trying to delete to the onDelete() function ?

I am a beginner. Please excuse me if this sounds trivial.

Thanks in advance !!

Upvotes: 1

Views: 2963

Answers (1)

Nimish
Nimish

Reputation: 1066

I think it should work to delete a document from the collection.

this.firestore
  .collection('comments')
  .doc(commentId)
  .delete()
  .then(res => {
     console.log('Product deleted Successfully');
   })
  .catch((error) => {
     console.error('Error removing document: ', error);
  });

Upvotes: 3

Related Questions