Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

288
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda