Gansonic
Gansonic

Reputation: 347

How to query Firebase by attribute of a child?

Schema:

Schema:

I'm trying to get all the objects filter by owner

To get a specific I do this:

var refCompaniesById = firebase.database().ref('companies').child(id);

But in this case I wanted to filter all

I tried:

ref.child('companies').child().set({"owner": id})

But I failed.

Upvotes: 5

Views: 2505

Answers (2)

adrice727
adrice727

Reputation: 1492

firebase.database().ref('companies').orderByChild('owner').equalTo(id)
  .once('value')
  .then(snapshot => {
    const records = snapshot.val();
    console.log(`Companies whose owner id is ${id}: `, records);
  })
  .catch(error => console.log(error));

Upvotes: 5

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

That would be done with a Firebase Database query:

var query = ref.child("companies").orderByChild("owner").equalTo(id);
query.on("child_added", function(snapshot) {
  console.log(snapshot.val());
});

This and more is covered in the Firebase Database documentation, but I also recommend Firebase for SQL developers.

Upvotes: 0

Related Questions