firebase - 如何从子集合 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 };
}, };
解决方案
const getCollection = (collection, id, subcollection) => {
const comments = ref(null);
const error = ref(null);
// Firestore listener
return { error, comments };
}
这里的初始值为comments
null 并且由于 Firebase 操作是异步的,因此可能需要一段时间才能加载数据,因此它会记录null
. 如果您使用comments
inv-for
那么可能会引发错误。
最好将初始值设置为空数组,以便在数据加载时不会引发任何错误:
const comments = ref([]);
此外,如果您要获取一次,请使用.get()
而不是onSnapshot()
推荐阅读
- python - Selenium:Chromedriver.exe 使用 if 中的函数自动退出
- python-3.x - 如何使用 PIL 或类似的东西用 yuv420 格式数据写入图像
- angular - Should i disable change detection during angular app init phase?
- apache-kafka - Create schema from JSON to write Parquet to HDFS with Kafka Sink
- c# - 良好实践 - C# 中的私有事件与私有方法
- javascript - Angular 2 - 使用 AOT 构建:Javascript 堆内存不足
- swift - 压缩我的音频文件后,为什么我不能播放文件?
- c# - 使用 .net 核心声纳扫描仪将声纳结果发布到 tfs 构建
- node.js - find all documents of all collections in db of mongoose using express
- ios - 斯威夫特:如何使所有正在运行的计时器无效?