Barbara Brina Barbara Brina - 1 month ago 17
Javascript Question

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 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?

Answer

You can use equalTo() like this to find any child by name:

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

You can find all the documentation here