Firebase search by child value

JavascriptFirebaseFirebase Realtime-Database

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBarbara BrinaView Question on Stackoverflow
Solution 1 - JavascriptGerard CuadrasView Answer on Stackoverflow
Solution 2 - JavascriptJoanView Answer on Stackoverflow