简体   繁体   English

如何使用其 ID 删除 Firebase/Firestore 集合中的文档?

[英]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".评论以“comments”的名称存储在 Firestore 集合中。 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 -我的comments.component.ts 文件代码如下 -

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.删除 function 将 cid 设为 null。 My question is, how can I pass the correct comment id of the comment I am trying to delete to the onDelete() function?我的问题是,如何将我要删除的评论的正确评论 ID 传递给 onDelete() function?

I am a beginner.我是初学者。 Please excuse me if this sounds trivial.如果这听起来微不足道,请原谅我。

Thanks in advance !!提前致谢 !!

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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM