Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

286
Views
how to remove an array item from firestore using JavaScript?

I'm trying to add a delete button to my page. the event listener callback is working properly except for the 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 is the object that contains the books array. In the console it always prints book deleted, but in the firestore console, nothing changes. this is a screenshot of the database.enter image description here

I would really appreciate any help and thank you.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I have replicated the behavior that you're experiencing. I tried changing the content of ${bookToDelete} to any word or even ID. It always returns book deleted even if its deleted or not. The line of code below should be changed in order to get the correct output.

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

I have created a workaround for your use-case with this kind of issue. See snippet below:

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

The workaround that I created will query the object in the array then remove the object in the array if it exist. After removing, it will query again to check if the object has been deleted and logs Book Deleted!. Vise versa for checking if the object doesn't exist on the 1st query, it will not proceed on removing them and logs No object found!.

The workaround itself can still be improved. You can add any logic you want for your use-case.


I'd also recommend to create a Feature Request if you want to have this kind of feature together with the arrayRemove Method.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!