Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading