【问题标题】:Trying to query firebase using where array-contains, how to wait for data to be received?尝试使用 where array-contains 查询 firebase,如何等待接收数据?
【发布时间】:2020-10-08 21:11:47
【问题描述】:

我在我的第一个现实生活中的 webdev 项目中使用 VueJS,但在尝试查询 Firebase 的 firestore 时遇到了麻烦。我正在为 Vue FYI 使用 VueFire 插件。我在 firebase 的“患者”集合中有用户,可以使用以下查询访问此患者列表:

const db = firebase.firestore();

export default {
  ...
  data () {
    return {
      email: firebase.auth().currentUser.email,
      therapistData: [],
      patientsList: []
    }
  },
  firestore () {
    return {
      therapistData: db.collection('Therapist').doc(this.email),
      patientsList: db.collection('Patient').where('practiceName', 'array-contains', 'TestPractice')
  }
}

每个患者都包含一个数组 practiceName,每个治疗师都包含一个字符串 practiceName。 patientList 应该给我一个对象,其中包含 Patient 集合中的每个患者,其中他们的 practiceName 数组包含当前登录的用户(治疗师)的 practiceName。

在我的 where 查询中对字符串(例如“TestPractice”)进行硬编码时,患者列表会按预期填充,我可以使用以下 vue 代码显示它:

<div v-for="(userItem, idx) in patientsList) :key="idx">
  <p>{{ patientsList[idx].firstName }} {{ patientsList[idx].lastName }}</p>
</div>

所以这段代码一切正常。我的问题是我正在尝试动态地(基于登录的治疗师)提取 practiceName 值,并将其作为第三个参数传递给我的 patientsList where 查询。所以它应该是:

patientsList: db.collection('Patient').where('practiceName', 'array-contains', this.therapistData.practiceName)

当我保存这段代码时,它给了我一个错误,说 where() 需要一个有效的第三个参数,并且得到“未定义”。为什么这是未定义的?当我在 vue {{ therapistData.practiceName }}

中渲染时
<button @click="patientsList(therapistData.practiceName)">Test method</button>
...
methods: {
  patientsList: function(practice) {
    console.log('Practice: ' + practice)
  }
}

我可以在控制台中看到therapistData.practiceName print 的正确值。谁能帮我理解或解决这个问题?为什么在我的 where() 查询中尝试使用 practiceName 时显示为未定义?

【问题讨论】:

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


    【解决方案1】:

    也许你需要做编程绑定

    export default {
      data() {
        return {
          therapistData: [],
        }
      },
    
      watch: {
        therapistData: {
          // call it upon creation too
          immediate: true,
          handler(therapistData) {
            this.$bind('practiseName', therapistData.practiseName)
          },
        },
      },
    }
    

    【讨论】:

    • 你能解释一下这是做什么的吗?我很难理解。这是我需要的所有代码,还是我需要将therapistData() 添加到我的created () 反对?
    • 抱歉,现在才查看评论。不,这不是所有的代码。它只是对你已有的东西的补充。所以你可以只添加上面的手表部分并尝试。 watch: { therapistData: { // call it upon creation too immediate: true, handler(therapistData) { this.$bind('practiseName', therapistData.practiseName) }, }, },
    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多