0

I am using the firebase functions on the firebase database to try and pull data but I am not being successful.

The data I want to search is structured like this:

enter image description here

The logic of what I want to do is the following: when a record is written to the 'jobs' collection, I want to then search the 'status' collection for availableStatus (stored as true/false).

For records that are true, I need to get the push IDs ('__zone_symbol__value') which are stored in the same 'status' collection.

In the path to the data I am after, there are two items that I will not know and need to use a wildcard, {time} and {uId}.

Here is my code I am using:

exports.notifyPeople = functions.database.ref('/jobs/{uId}/status')
    .onWrite(event => {
      var dbRead = admin.database().ref('status/worker/{time}/{uId}/pushToken').orderByChild('availableStatus').equalTo('true').on("child_added", function(snapshot) {
          console.log(snapshot.val());
        });

          const getPushTokens = dbRead.child;
      }

What am I doing wrong?

Baub
  • 723
  • 4
  • 21
  • 36

1 Answers1

3

While functions.database.ref('/jobs/{uId}/status') can be used in Cloud Functions to determine what paths the function will trigger on, it cannot be used as a wildcard when reading from the database here: admin.database().ref('status/worker/{time}/{uId}/pushToken').

You will have to either know the time and uId that you want to read and use them like this:

let time = ...;
let uId = ...;
admin.database().ref(`status/worker/${time}/${uId}/pushToken`)

Or you will have to read all information for from all workers:

admin.database().ref("status/worker");

If that means that you're reading way too much data, consider adding additional data to your JSON to allow this look up to be more efficient. For example, if you keep a list of tokens for nodes that have availableStatus set to true, the lookup can be quite simple. For another example of this, see my answer here: Firebase Query Double Nested

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • That was what I needed. A couple of follow up questions. I am now using this code: var dbRead = admin.database().ref('status/driver/').on("child_added", function(snapshot) { console.log(snapshot.val()); }); how do I get the results of snapshot.val so I can use them? I can't seem to access it outside of that function. Second, once I can read use that var, how should I read it with the variables in the path? – Baub Jan 27 '18 at 23:42
  • That first problems sounds like the very tradition async 101 problem: Firebase loads data asynchronously, so you'll have to use it in the scope where it becomes available. See https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener, https://stackoverflow.com/questions/35419303/firebase-use-query-result-outside-function – Frank van Puffelen Jan 27 '18 at 23:52