使用集合中的特定文档 ID 遍历多个文档

iterate through multiple document with certain doc id from a collection

希望你写得很好,我正在使用 firebase 和 vue js 构建一个消息应用程序。 每个用户都有一个文档,每个文档中都有一个名为 includeInMsg 的字段,其中包含用户包含的消息的 Id。我知道如何通过其 id 读取一个文档,但我不知道如何通过它们的 id 读取多个文档。 在这里你可以看到我的代码:

import { ref } from "vue";
import { db } from "src/boot/firebase";
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { updateDoc, arrayUnion, arrayRemove } from "firebase/firestore";
import {
  addDoc,
  collection,
  query,
  where,
  getDocs,
  getDoc
} from "firebase/firestore";
import { doc, onSnapshot } from "firebase/firestore";

export default {
  setup() {
    return {
      userList: ref([]),
      userMessageRefList: ref([]),
      userMessageDocList: ref([]),
      freelancerProfile: ref([]),
      messages: ref([]),
      userMessage: ref([]),
      listofdata: ref([])
    };
  },
  async created() {
    // check if user loged in or not
    const auth = getAuth();
    onAuthStateChanged(auth, user => {
      if (user) {
        // store current user uid in userlist
        this.userList.unshift(user.uid);
        this.renderMessageList();
      } else {
        this.$router.push("/");
      }
    });
  },
  methods: {
    // render user message list doc id
    async renderMessageList() {
      const currentUserProfile = query(
        collection(db, "userProfile"),
        where("uuid", "==", this.userList[0])
      );
      const userProfileQuerySnapshot = await getDocs(currentUserProfile);
      userProfileQuerySnapshot.forEach(doc => {
        let docData = doc.data();
        this.userMessageRefList.unshift(docData.messageList);
        this.listofdata.unshift(docData);
      });
      this.userMessageRefList.forEach(elem =>
        // store doc id into userMessageDocList
        elem.forEach(le => this.userMessageDocList.unshift(le))
      );
      console.log(this.userMessageDocList) //output: {0: {…}, 1: {…}}
      // now I need to read each document by their doc Id and store it in an array to render

    },
  },
  computed: {
    checkMessages: function() {
      if (this.messages.length > 1) {
        return true;
      } else {
        return false;
      }
    }
  }
};

我尝试使用 for 循环读取每个文档并将值存储在一个数组中,但出现 SyntaxError: Unexpected reserved word 'await'. (71:26) 错误。

如评论中所确认,this.userMessageDocList 包含一个复合对象,其中包含具有文档 ID 的对象。

在这种情况下,您应该使用 Promise.all() 触发对 Firestore 的可变数量的并行调用。

如文档中所述(参见上文 link):

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.


因此您需要遍历该对象,获取文档 ID 并填充您传递给 Promise.all() 的承诺数组。在伪代码中(我让你使用你想要遍历对象的方法,SO 上有很多例子)它是按照以下几行:

const promisesArray = [];

<Loop For each element>
   // Assumption: element.docId contains the Firestore doc ID
   promisesArray.push(getDoc(doc(db, "yourCollection", element.docId)))

</End Loop>

const docSnapshotsArray = await Promise.all(promisesArray);
docSnapshotsArray.forEach(docSnap => {
   console.log(docSnap.data());
   // ...
});

docSnapshotsArraysDocumentSnapshots 的数组。然后你可以遍历这个数组并做任何你想做的事。


我现在不知道这对你的具体情况是否重要,但请注意,对于 Promise.all(),结果数组中的 返回值将按照承诺传递的顺序排列,不管完成顺序如何。