【问题标题】:Firestore query with where returning undefined snapshot (Vue.js / Firestore / Vuefire)Firestore 查询返回未定义快照的位置(Vue.js / Firestore / Vuefire)
【发布时间】:2021-05-02 10:20:50
【问题描述】:

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

Firestore 数据库只有一个集合,其中包含几个用户:

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

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

<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 子句不起作用。

【问题讨论】:

标签: javascript firebase vue.js google-cloud-firestore vuefire


【解决方案1】:

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

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

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

  db.collection("users")
    .where("uid", "==", this.$store.state.user.uid)
    .get()
    .then((snapshot) => {
      const documents = snapshot.docs.map(doc => doc.data())
      // do something with documents
   })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多