0

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
eat-sleep-code
  • 4,753
  • 13
  • 52
  • 98

1 Answers1

2

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I just realized my example may have been a bit confusing. order is a pre-specified sort order that I want to sort by. I am trying to match on tripId. Since the orderBy seems to dictate the "field" I am looking at for equalTo, how do I do a sort and a query. – eat-sleep-code Jan 16 '17 at 06:49
  • I added a snippet for how to order on a property in the second JSON structure. The first JSON structure won't allow that, since a Firebase Database query can only contain one `orderBy` clause. See http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Jan 16 '17 at 16:58