【问题标题】:Firebase query with Vue js使用 Vue js 进行 Firebase 查询
【发布时间】:2019-10-03 19:56:41
【问题描述】:

我是 Vue JS 和 Firebase 的新手。我的目标是获取所有具有相同类别的“事件”。我的意思是,让我有两个 eventos,一个 eventos 类别“SMIX”,另一个有“DAM”。现在我想获得 eventos 的类别'SMIX'

我的数据结构在这里:

 created() {
            var datos = []

            firebase.database().ref('usuarios').on("value", data => {

                data.forEach(function(user){
                    user.child("eventos").orderByChild("categoria").equalTo("SMIX")
                        .forEach(function(evento){
                        datos.push(evento.val())
                    });
                });

                this.eventos = datos;
            });
        }[My data Structure][1]

【问题讨论】:

  • 你从请求中得到了什么?
  • @EduardoLeite 我收到此错误 user.child(...).orderByChild is not a function
  • 你为什么不使用 orderbychild 和 equalTo 来完成你的请求?你不会遇到这个问题,响应会更小
  • 我没听懂你。可以举个例子吗?
  • 嗨,我做到了你说的 user.child("eventos").ref.orderByChild("categoria").equalTo("SMIX")

标签: firebase vue.js firebase-realtime-database


【解决方案1】:

您的代码中有几个错误和需要注意的地方:

首先,如果您收到错误user.child(...).orderByChild is not a function 这是因为对于data.forEach(function(user) {...})user 是一个DataSnapshot(请参阅forEach() 文档),并且通过在此DataSnapshot 上调用child() 方法,您会得到另一个DataSnapshot...有一个orderByChild() 方法。

orderByChild()方法是Reference的方法,所以你需要这样做

user.child(...).ref.orderByChild()

使用DataSnapshotref 属性


其次,你不能这样做

user.ref.child("eventos").orderByChild("categoria").equalTo("SMIX")
                        .forEach()

因为您需要使用once()on() 方法在Reference 表示的数据库位置获取数据。


第三,由于要在一个循环中执行多个查询,因此需要使用once() 方法而不是on() 方法。 on() 方法设置了一个持续“监听特定位置的数据变化”的监听器。


最后,请注意您需要使用Promise.all() 来管理对数据库的并行异步查询。


所以,在注意到以上所有要点之后,下面的代码就可以解决问题(输入created()):

        var datos = []

        firebase.database().ref('usuarios').once('value')
        .then(dataSnapshot => {
            var promises = [];
            dataSnapshot.forEach(user => {    
                promises.push(user.ref.child("eventos").orderByChild("categoria").equalTo("SMIX").once('value'));
            });
            return Promise.all(promises);
        })
        .then(results => {
            //console.log(results);
            results.forEach(dataSnapshot => {
                dataSnapshot.forEach(evento => {
                    datos.push(evento.val());
                });     
            });
            this.eventos = datos;
        });

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多