0

I need to call Firebase DB inside Firebase Function. Here is how my DB structure looks: enter image description here

I need to get LastName by FirstName. I've tried a lot of ways and nothing works for me. Here is one of them:

    var db = admin.database();
    var ref = db.ref("people");
     ref.equalTo("Alex").on("child_added", function(snapshot) {
            console.log(snapshot.key);
     });

What am I do wrong?

1
  • If you are new to JavaScript and/or interacting with Firebase from it, Cloud Functions for Firebase is not the best way to learn it. I recommend first reading the Firebase documentation for Web developers and/or taking the Firebase codelab for Web developer. They cover many basic JavaScript, Web and Firebase interactions. After those you'll be much better equipped to write code for Cloud Functions too. Commented Jan 19, 2018 at 1:47

1 Answer 1

2

You're not telling Firebase what field to order/filter on. So what property do you want to be equal to Alex?

To tell the database this, you call orderByChild(...) before equalTo(...):

var db = admin.database();
var ref = db.ref("people");
ref.orderByChild("FirstName").equalTo("Alex").on("child_added", function(snapshot) {
    console.log(snapshot.key);
});

This will work in a web client, which will just keep an open connection to the Firebase Database while the page is open. But in Cloud Functions your code will be shut down quickly, so you'll want to typically read using once("value",...):

ref.orderByChild("FirstName").equalTo("Alex").once("value", function(snapshot) {
    snapshot.forEach(function(child) {
        console.log(child.key);
    });
});

If you run this code in Cloud Functions, you need to tell Cloud Functions when you're done. To do this, you return a so-called promise from your code. A simple way here is to do:

return ref.orderByChild("FirstName").equalTo("Alex").once("value", function(snapshot) {
    snapshot.forEach(function(child) {
        console.log(child.key);
    });
    return Promise.resolve();
});

So in the callback we return a resolved promise once we're done. And then our outer code returns that to the Cloud Functions environment, so that it knows that your code it done.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.