【问题标题】:How to get all items from subcollection Firebase Firestore Vue如何从子集合 Firebase Firestore Vue 中获取所有项目
【发布时间】:2021-11-04 08:46:50
【问题描述】:

如何从子集合中获取所有的 cmets?

这是我获取 cmets 集合的可重用函数。

    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(cmets) 它的 null 时,在快照中 doc.data() 很好,但不知何故,即使我将 doc.data() 推送到结果数组并将其传递给 cmets.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 };

}, };

【问题讨论】:

  • getAllComments() 定义在哪里?
  • @Dharmaraj 我为可重用函数(firebase 函数)创建了可组合文件夹,以获取集合、发布集合、获取单个文档等。
  • 您能否用完整的代码更新您的问题,以便我们查看该函数的作用?
  • @Dharmaraj 这是我的函数所做的,变量 projectFirebase 是 firebase.firestore();我的函数需要参数,在 Comments.vue 中我导入这个文件,如 import getAllComments.js from '@/composables/getAllComments' 和在设置函数中我销毁 const {cmets} 中的 cmets 并使用 REAL 参数调用函数。我希望你能理解我,我的英语不好,谢谢
  • @PeterO。它的工作原理是这样的

标签: firebase vue.js google-cloud-firestore vue-composition-api


【解决方案1】:
const getCollection = (collection, id, subcollection) => {
  const comments = ref(null);
  const error = ref(null);

  // Firestore listener

  return { error, comments };
}

这里comments 的初始值为null,由于Firebase 操作是异步的,数据加载之前可能需要一段时间,因此它会记录null。如果您在v-for 中使用comments,则可能会引发错误。

最好将初始值设置为空数组,这样在加载数据时就不会抛出任何错误:

const comments = ref([]);

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

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 1970-01-01
    • 2021-09-18
    • 2021-05-09
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多