0

I've been struggling with creating a firebase query all day!

The below query returns the data as an array from my Firebase realtime database:

exports.getCountry = () => {
  return database
    .ref("/countries")
    .once("value")
    .then(data => data.val());
};

This returns the below from the database in the format Array of Objects,

[
    {"id":1, "country":"singapore", "population":15000000},
    {"id":2, "country":"hongkong", "population":12000000},
    {"id":2, "country":"vietnam", "population":2250000}
]

However I want to query the database to just return one record, something along the lines of

exports.getCountry = () => {
  return database
    .ref("/countries")
    .where('id'===1)
    .once("value")
    .then(data => data.val());
};

would return a single line from my database:

{"id":1, "country":"singapore", "population":15000000}

however I can't get this to work! It should be simple, but I can't get it to play ball!

1 Answer 1

1

I referenced these Firebase docs on complex queries.

Piecing together the examples they provide, I think your query should look something like:

var ref = db.ref("countries");

ref.orderByChild("id").equalTo(1).on("value", function(snapshot) {
    snapshot.forEach( data => {
        console.log(data.val());
    });
});

*untested

EDIT:

The docs I linked are to the admin SDK, if you are doing this on the front end with JavaScript, it should still work. The JavaScript SDK appears to have the same query structure - shown in these docs for the JS SDK too.

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.