簡體   English   中英

如何使用 JavaScript 從 firestore 中刪除數組項?

[英]how to remove an array item from firestore using JavaScript?

我正在嘗試向我的頁面添加一個刪除按鈕。 除了 updateDoc function 之外,事件偵聽器回調正常工作。

const deleteBook = document.getElementsByClassName('deleteBook');
for (let i = 0; i < deleteBook.length; i++) {
    deleteBook[i].addEventListener('click', async () => {
        //book to delete
        const bookToDelete = deleteBook[i].parentElement.firstElementChild.textContent
        // collection title to delete the book from 
        const bookCol = deleteBook[i].parentElement.parentElement.parentElement.firstElementChild.textContent
        // get a snap of the database
        const docRef = doc(dataBase, 'users', `${auth.currentUser.uid}`)
        const docSnap = (await getDoc(docRef)).data();
        // loop over the collections and get a match with the bookCol
        for (const col in docSnap) {
            if (docSnap[col].title === bookCol) {
                console.log('col to delete from found')
                console.log(`book to delete ${bookToDelete}`)
                await updateDoc(doc(dataBase, 'users', `${auth.currentUser.uid}`), {
                    [`${col}.books`]: arrayRemove(`${bookToDelete}`)
                }).then(()=>{
                    // fullfiled
                    console.log('book deleted')
                }, ()=>{
                    // rejected
                    console.log('promis rejected')
                })    
            }
        } 
    })
}   

Col 是包含書籍數組的 object。 在控制台中,它總是打印已刪除的書,但在 firestore 控制台中,沒有任何變化。 這是數據庫的屏幕截圖。 在此處輸入圖像描述

我真的很感激任何幫助,謝謝。

我已經復制了您正在經歷的行為。 我嘗試將${bookToDelete}的內容更改為任何單詞甚至 ID。 它總是返回已刪除的book deleted ,無論是否刪除。 為了獲得正確的 output,應該更改下面的代碼行。

.then(()=>{
   // fullfiled
   console.log('book deleted')
}, ()=>{
   // rejected
   console.log('promis rejected')
})    

對於此類問題,我已經為您的用例創建了一個解決方法。 請看下面的片段:

const db = getFirestore();

const colName = "users";
const arrayName = "books";
const usersCol = collection(db, colName);
const userRef = doc(db, colName, `${auth.currentUser.uid}`);
const arrayRef = `${col}.${arrayName}`;
const q = query(usersCol, where(arrayRef, "array-contains", `${bookToDelete}`));

const querySnapshot = await getDocs(q)
.then((querySnapshot) => {
    // Removal of object will not proceed if the querySnapshot is empty.
    if ((querySnapshot.empty)) {
        console.log("No object found!");
    }
    else {
        // Proceeds to removal of object.
        updateDoc(userRef, {
            [arrayRef]: arrayRemove(`${bookToDelete}`)
        })
        .then(() => {
            // Check again if the object was deleted successfully.
            const querySnapshot = getDocs(q)
            .then((querySnapshot) => {
                if ((querySnapshot.empty)) {
                    console.log("Book Deleted!");
                }
                else {
                    console.log("Failed!");
                }
            })
        });
    }
})
// Catch if there are any Firebase errors.
.catch(error => console.log('Failed!', error));

我創建的解決方法將查詢數組中的 object,然后刪除數組中的 object(如果存在)。 刪除后會再次查詢object是否被刪除,記錄Book Deleted! . 反之亦然,如果 object 在第一個查詢中不存在,它將不會繼續刪除它們並記錄No object found! .

解決方法本身仍然可以改進。 您可以為您的用例添加任何您想要的邏輯。


如果您想將這種功能與arrayRemove方法一起使用,我還建議您創建一個功能請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM