【问题标题】:Firestore, Vue.js, can't get value from document with .get()Firestore,Vue.js,无法使用 .get() 从文档中获取价值
【发布时间】:2020-09-07 11:58:18
【问题描述】:

我不知道如何将返回的项目从 firebase 文档获取到变量中。我尝试以下操作并收到以下错误: 获取传感器文档时出错:TypeError: Cannot set property 'node_addr' of undefined

我声明了变量,并且代码行 console.log("Document data:", doc.data()) 确实返回了整个文档对象,因此它似乎正在检索文档。该文档确实包含字段“node_addr”,这是一个填充在目标测试文档上的数字字段。我正在尝试将此值放入 this.node_addr

如果我查询一个搜索特定值的集合,同样的过程确实有效,但是当我尝试查询具有已知名称的特定文档时,我得到了错误。我认为我的语法有一些小问题。

请帮忙。谢谢!

<script>
import db from '../components/firebaseInit'
export default {
    name: 'sensor-edit',
    data () {
        return {
            node_addr: 0,
            node_chan: 0,
            target_sensor_doc: ''
        }
    },
    created () {
        this.target_sensor_doc = this.$route.params.sensor_record.id

        var docRef = db.collection('sensors').doc(this.target_sensor_doc.toString())
        docRef.get().then(function(doc) {

                this.node_addr = doc.data().node_addr
                console.log("Document data:", doc.data())

        }).catch(function(error) {
            console.log("Error getting sensor document:", error);
        })
    }
}
</script>

【问题讨论】:

  • 请编辑问题以准确显示 this.target_sensor_doc.toString() 的值以及您尝试获取的相关文档。
  • 使用箭头函数,即.then(doc =&gt; { this.node_addr = doc...
  • @Phil 谢谢先生!!您的箭头函数示例和语法的实际示例做到了。不幸的是,我不明白您共享的链接中发布的内容。我的大脑无法将 MyConstructor 连接到 Firestore 查询。 :) 你是我今天最喜欢的人。这结束了几天的沮丧。再次感谢!!
  • 比较一下,MyConstructor 相当于你的 Vue 组件,transport.on() 相当于 docRef.get().then()

标签: vue.js google-cloud-firestore


【解决方案1】:

谢谢@菲尔!!!!这正是我所需要的。我已经为此奋斗了好几天了。

对于以后需要这个的其他人......这是正确的工作查询:

created () {
    this.target_sensor_doc = this.$route.params.sensor_record.id
    var docRef = db.collection('sensors').doc(this.target_sensor_doc.toString())
        docRef.get().then(doc => {
            this.node_addr = doc.data().node_addr
        })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-07
    • 2021-11-13
    • 2018-12-06
    • 1970-01-01
    • 2022-01-20
    • 2019-05-24
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多