Firebase query with Vue js

Asked by At

i am new in Vue JS and in Firebase. My target is get all 'eventos' that has same category. I mean, let's i have two eventos, an eventos category "SMIX" and another has "DAM". Now i want to get the eventos has category 'SMIX'

My data structure is here : enter image description here

 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]

1 Answers

1
Renaud Tarnec On Best Solutions

There are several errors and points to be noted in your code:

Firstly, if you receive the error user.child(...).orderByChild is not a function it is because with data.forEach(function(user) {...}), user is a DataSnapshot (see the forEach() doc), and by calling the child() method on this DataSnapshot you get another DataSnapshot... which does not have a orderByChild() method.

The orderByChild() method is a method of a Reference, so you need to do

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

using the ref property of the DataSnapshot


Secondly, you cannot do

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

because you need to use the once() or on() methods to get the data at a database location represented by a Reference.


Thirdly, Since you are going to execute several queries within a loop, you need to use the once() method instead of the on() method. The on() method set a listener that continuously "listens for data changes at a particular location."


Finally, note that you need to use Promise.all() to manage the parallel asynchronous queries to the database.


So, having noted all the points above, the following code will do the trick (to put in 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;
        });