我无法从Firebase Firestore数据库中删除单个文档

时间:2020-06-18 06:17:30

标签: reactjs firebase google-cloud-firestore

我创建了一个React应用,其中列出了书名和作者姓名。数据存储在firebase firestore数据库中,并且与前端的应用程序同步。我遇到的问题是要从集合中删除单个文档。我可以访问该ID,但无法选择要删除的特定ID。我将代码放在下面,希望有人可以帮助我展示如何删除单个文档,同时删除所有文档。谢谢!

import React, {useState, useEffect} from 'react'
import firebase from '../config/fbConfig'


const useBooks = () => {
    const [books, setBooks] = useState([])
     useEffect(() => {
        firebase.firestore().collection('books').onSnapshot((snapshot) => {
            const newBooks =  snapshot.docs.map(doc => ({
                 id: doc.id,
                ...doc.data()
              }))
            setBooks(newBooks)
        })
    },[])
    return books
}

const handleOnClick = () => { 
    const db = firebase.firestore()
    db.collection('books').get().then(snapshot => {
        snapshot.docs.forEach(doc => {
            const id = doc.id
            db.collection('books').doc(id).delete() 
            console.log("Jampa thinlay Book ID:", id)
        }) 

    })     
}

const BookList = () => {
    const books = useBooks()
    console.log('jt books', books)
    return(
        <div className="book_list">
            <ul>
                {
                    books.map(book => 
                         <li key={book.id} onClick={()=> handleOnClick()} >
                            <div className="title">id:{book.id}</div>
                            <div className="cross" > X </div>
                            <div className="title">book:{book.title.title}</div>
                            <div className="author">author: {book.author.author}</div>
                         </li>      
                    )
                } 
            </ul>
        </div>
    )
}
export default BookList

1 个答案:

答案 0 :(得分:1)

问题在于您的函数中

var nameVal = $('[name=1]').attr('value');
$("#countryselect").val(nameVal)

您正在循环浏览所有文档,并在每个文档上调用delete,然后发生问题。

一种解决方法是更改​​const handleOnClick = () => { const db = firebase.firestore() db.collection('books').get().then(snapshot => { snapshot.docs.forEach(doc => { const id = doc.id db.collection('books').doc(id).delete() console.log("Jampa thinlay Book ID:", id) }) }) } 函数的签名,以接收要删除的项目的ID,就像

handleOnClick

新功能的区别在于,它接收要删除的文档的const handleOnClick = (documentId) => { const db = firebase.firestore(); db.collection("books").doc(documentId).delete() .then(() => { console.log("item with id" + documentId + "got deleted"); }).catch((e) => console.log(e)); } ,并且仅删除该文档,

并且在您的html中,您可以按以下方式传递每本书的ID

id