返回未定义快照的 Firestore 查询Vue.js / Firestore / Vuefire

问题描述

我目前正在使用支持 vuefire 的 Firestore/Vue.js。

Firestore DB 只有一个集合,里面有几个用户

  • 用户
    • 001
      • 姓名:杰克
      • uid:{Firebase 身份验证 ID}
      • org_id:123
    • 002
      • 姓名:弗兰克
      • uid {Firebase 身份验证 ID}
      • org_id:456

在 Vue 组件中,我尝试查询数据库以使用身份验证 ID(当前存储在 Vuex Store 中)获取一个用户

<script>
import { db } from "../main.js";    
export default {
  data() {
    return {
      items: [] // to be used later
    };
  },created() {
    this.getServices();
  },methods: {
    getServices() {
      console.log(this.$store.state.user.uid);
      db.collection("users")
        //.doc("001")
        .where("uid","==",this.$store.state.user.uid)
        .get()
        .then((snapshot) => {
          console.log(snapshot);
          if (snapshot != null && snapshot.data != null) {
            const user = snapshot.data();
            // do something with document
            let org_id = user["org_id"];
            console.log("org id:" + org_id);
          } else {
            console.log("No data returned!");
          }
        });
    },},};
</script> 

代码总是返回一个空的快照。我已执行的检查:

  • 使用文档 ID 直接访问文档是可行的
  • this.$store.state.user.uid 设置正确
  • 对 where 子句中的 uid 进行硬编码会产生相同的错误

我是一个完全的初学者,但在我看来 where 子句不起作用。

解决方法

由于您使用 foo 定义了 Query,因此 db.collection("users").where("uid","==",this.$store.state.user.uid) 对象实际上是一个 QuerySnapshot 而不是 DocumentSnapshot

所以 snapshot 总是 snapshot.data != null,因为 false 没有这样的属性。对于 QuerySnapshot => 也是如此,它总是 snapshot.data() != null,因为 false 没有这样的方法

您应该使用 forEach() 方法循环 QuerySnapshot 或在 docs 属性上使用 QuerySnapshot,如 Vuefire example 中所示(请参阅“检索集合"):

map