Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase search by child value

I have the following structure on my Firebase database: firebase database

I would like to search for an user by name, last name or email but as I don't have the user key in the level above I don't know how I can achieve this. I'm doing and administrator session so it wouldn't have access to the user key.

I have tried:

let usersRef = firebase.database().ref('users'); usersRef.orderByValue().on("value", function(snapshot) {     console.log(snapshot.val());     snapshot.forEach(function(data) {         console.log(data.key);     }); }); 

But it brings all the users on the database. Any ideas?

like image 452
Barbara Brina Avatar asked Nov 07 '16 17:11

Barbara Brina


People also ask

What is limitToFirst in Firebase?

The limitToFirst() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message.

What is AngularFireDatabase?

AngularFireDatabase is a service which can be injected through the constructor of your Angular component or @Injectable() service. In the previous step, we modified the /src/app/app. component. ts to retrieve data as an object.

What is DataSnapshot in Firebase?

A DataSnapshot instance contains data from a Firebase Database location. Any time you read Database data, you receive the data as a DataSnapshot.


2 Answers

You can use equalTo() to find any child by value. In your case by name:

ref.child('users').orderByChild('name').equalTo('John Doe').on("value", function(snapshot) {     console.log(snapshot.val());     snapshot.forEach(function(data) {         console.log(data.key);     }); }); 

The purpose of orderByChild() is to define the field you want to filter/search for. equalTo() can get an string, int and boolean value.

Also can be used with auto generated keys (pushKey) too.

You can find all the documentation here

like image 164
Gerard Cuadras Avatar answered Sep 20 '22 11:09

Gerard Cuadras


A warning to avoid unpleasant surprises: when you use orderByChild and equalTo do not forget to add an index on your data (here's the doc)

If you don't all the nods will be downloaded and filtered client side which can become very expensive if your database grows.

like image 32
Joan Avatar answered Sep 19 '22 11:09

Joan