0

I am using Firebase cloud code and firebase realtime database.

My database structure is:

 -users
       -userid32
       -userid4734
          -flag=true  
       -userid722
          -flag=false
       -userid324

I want to query only the users who's field 'flag' is 'true' .

What I am doing currently is going over all the users and checking one by one. But this is not efficient, because we have a lot of users in the database and it takes more than 10 seconds for the function to run:

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.test1 = functions.https.onRequest((request, response) => {
    // Read Users from database
    //
    admin.database().ref('/users').once('value').then((snapshot) => {
        var values = snapshot.val(),
            current, 
            numOfRelevantUsers,
            res = {};       // Result string

            numOfRelevantUsers = 0;

        // Traverse through all users to check whether the user is eligible to get discount.
        for (val in values) 
        {
            current = values[val]; // Assign current user to avoid values[val] calls.

            // Do something with the user
        }

        ...
});

Is there a more efficient way to make this query and get only the relevant records? (and not getting all of them and checking one by one?)

1 Answer 1

2

You'd use a Firebase Database query for that:

admin.database().ref('/users')
    .orderByChild('flag').equalTo(true)
    .once('value').then((snapshot) => {
    const numOfRelevantUsers = snapshot.numChildren();

When you need to loop over child nodes, don't treat the resulting snapshot as an ordinary JSON object please. While that may work here, it will give unexpected results when you order on a value with an actual range. Instead use the built-in Snapshot.forEach() method:

snapshot.forEach(function(userSnapshot) {
  console.log(userSnapshot.key, userSnapshot.val());
}

Note that all of this is fairly standard Firebase Database usage, so I recommend spending some extra time in the documentation for both the Web SDK and the Admin SDK for that.

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.