Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

65
Vistas
how to get the document reference of a document in a collection when iterating through the documents

I am trying to remove an array element from an array in a document using the method updateDoc, for that I need the document reference however I do not know how to get it as it was one generated by Firebase and the documentation or past questions have not helped. This is my code:

   const subjectRef = collection(db, "users", auth.currentUser.uid, "subjects");
const querySnapshot = await getDocs(subjectRef);

subjects.forEach(subject => {
    querySnapshot.forEach((doc) => {
      if(doc.data().Subject == subject) {
        const subject = doc.data();
        const subjectName = subject.Subject;
        const topics = subject.Topics;
        //iterates through the topics of the subjects
        globalTopicList.forEach(obj => {
          topics.forEach(async topic => {
            if(obj[1]==topic.id) {
              const temp = {
                Topic: topic.Topic,
                Days: 0,
                Rating: topic.Rating,
                id: topic.id,
              };
              await updateDoc(docRef, {
                Topics: arrayRemove(topic.id)
              });
              console.log('done');
            }
          });
        });
      }
    });
  });
  
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Each QueryDocumentSnapshot has a .ref property that is the DocumentReference of that document:

const updates = [];
querySnapshot.forEach((doc) => {
  const docRef = doc.ref
  
  updates.push(updateDoc(docRef, {...updatedData}))
})

return Promise.all(updates).then(() => {
  console.log("Documents updated")
}).catch((e) => console.log(e))

If you are updating less than 500 documents, then you can update them at once using a Batched Write:

import { writeBatch, doc } from "firebase/firestore"; 

const batch = writeBatch(db);

querySnapshot.forEach((doc) => {
  const docRef = doc.ref
  
  batch.update(docRef, {...updatedData}))
})

// Commit the batch
await batch.commit();
7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.