首页 > 解决方案 > 如何从子集合 Firebase Firestore Vue 中获取所有项目

问题描述

如何从子集合中获取所有评论?

这是我的可重用函数来获取评论集合。

    import { ref, watchEffect } from 'vue';
    import { projectFirestore } from '../firebase/config';

    const getCollection = (collection, id, subcollection) => {
    const comments = ref(null);
    const error = ref(null);

    // register the firestore collection reference
     let collectionRef = projectFirestore
    .collection(collection)
    .doc(id)
    .collection(subcollection);

    const unsub = collectionRef.onSnapshot(
    snap => {
      let results = [];
      snap.docs.forEach(doc => {
        doc.data().createdAt && results.push(doc.data());
      });

      // update values
      comments.value = results;
      error.value = null;
    },
    err => {
      console.log(err.message);
      comments.value = null;
      error.value = 'could not fetch the data';
    }
    );

    watchEffect(onInvalidate => {
      onInvalidate(() => unsub());
    });

       return { error, comments };
    };

    export default getCollection;

这是我的 Comments.vue,我在 setup() 函数(组合 API)中传递参数

const { comments } = getAllComments('posts', props.id, 'comments');

当我 console.log(comments) 它的 null 时,在快照中 doc.data() 很好,但是即使我将 doc.data() 推送到结果数组并将其传递给 comments.value,结果也是空数组。

有人可以帮助我如何获得该子集合吗?

这是我的 Comment.vue 组件

   export default {
    props: ['id'],
   setup(props) {
const { user } = getUser();
const content = ref('');

const { comments } = getAllComments('posts', props.id, 'comments');

const ownership = computed(() => {
  return (
    comments.value && user.value && user.value.uid == comments.value.userId
  );
});

console.log(comments.value);
}

return { user, content, handleComment, comments, ownership };

}, };

标签: firebasevue.jsgoogle-cloud-firestorevue-composition-api

解决方案


const getCollection = (collection, id, subcollection) => {
  const comments = ref(null);
  const error = ref(null);

  // Firestore listener

  return { error, comments };
}

这里的初始值为commentsnull 并且由于 Firebase 操作是异步的,因此可能需要一段时间才能加载数据,因此它会记录null. 如果您使用commentsinv-for那么可能会引发错误。

最好将初始值设置为空数组,以便在数据加载时不会引发任何错误:

const comments = ref([]);

此外,如果您要获取一次,请使用.get()而不是onSnapshot()


推荐阅读