eat-sleep-code
eat-sleep-code

Reputation: 4855

Filtering firebase data and ordering results

I am writing an HTML/JavaScript app that uses Firebase as the database.

My data is structured somewhat like this:

steps/
- GUID
-- tripId
-- name
-- description
-- order
-- launchDate

I want to select any items from steps whose tripId matches a specific value (passed in a variable). I then want to order the results by descending order.

I am more use to T-SQL type syntax so am getting confused in the world of realtime databases.

Here is a snippet of what my code looks like now.

var steps = function readSteps(format, tripId) {
    var stepsRef;
    stepsRef = firebase.database().ref('steps/');
    stepsRef.orderByChild('order').on('value', function (response) {
        // DO SOME LOGIC HERE WITH 'response' DATA
    });
}

I don't know how to filter these results and I don't see how to easily do a descending sort. order is an integer.

Upvotes: 0

Views: 1248

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

For getting all steps for order 42, you'd query with:

stepsRef = firebase.database().ref('steps/');
stepsRef.orderByChild('order').equalTo(42).on('value', function (snapshot) {
    snapshot.forEach(function(stepSnapshot) {
        console.log(stepSnapshot.key, stepSnapshot.val());
    });
});

But if you're always going to be looking up the steps for an order, you're better off modeling the JSON differently:

orderSteps
  order42
    step1: ...
    step2: ...
    step3: ...
  order43
    step1: ...
    step2: ...

This allows you to retrieve the steps for an order, without needing a query:

stepsRef = firebase.database().ref('orderSteps/order42');
stepsRef.on('value', function (snapshot) {
    snapshot.forEach(function(stepSnapshot) {
        console.log(stepSnapshot.key, stepSnapshot.val());
    });
});

If you also want to order this result on a child property, it'd become:

stepsRef.orderByChild("field").on('value', function (snapshot) {

I recommend reading NoSQL data modeling and viewing Firebase for SQL developers to learn more about modeling data in a NoSQL database.

Upvotes: 2

Related Questions