遍历文档时如何获取集合中文档的文档引用

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

我正在尝试使用 updateDoc 方法从文档中的数组中删除数组元素,为此我需要文档参考,但我不知道如何获取它,因为它是由 Firebase 和文档生成的或过去的问题没有帮助。 这是我的代码:

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

该文档的每个 QueryDocumentSnapshot has a .ref property that is the DocumentReference

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

如果您要更新的文档少于 500 个,那么您可以使用 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();