Home > Back-end >  how to get the document reference of a document in a collection when iterating through the documents
how to get the document reference of a document in a collection when iterating through the documents

Time:04-17

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

CodePudding user response:

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();
  • Related