How can I access data entries in Firebase that have a particular key?

I've got some data stored in firebase with a structure like this:

"application": {
  "companies": {
    "firebase": {
      "creation": {
        "name": "Firebase Inc",
        "location": "USA"
      },

      "google": {
        "creattion": {
          "name": "Google Inc",
          "location": "USA"
        }
      }

      "facebook": {
      },

      "apple": {
      }
    }
  }
}

There are numerous records under the companies key. How can I efficiently execute the following queries?

Is there a way to query only the records that have the key creation present under their name?

And how about querying only the records that do NOT have the key creation present under their name?

Additionally, I'd like to use .on('child_added') on the returned results so that I can process those specific records later. Is that something achievable?

Answer №1

UPDATE: Easier method without the need for an additional parameter

Queries

Below are the queries that can be used to achieve this without requiring an extra parameter:

  • Locate the companies without a creation attribute:
    • var ref = new Firebase(fbUrl+'/companies').orderByChild("creation").equalTo(null);
  • Locate the companies with a creation attribute:
    • var ref = new Firebase(fbUrl+'/companies').orderByChild("creation").startAt(!null);
  • To your rules, you should add ".indexOn": "creation".

Update 2: I conducted an experiment by adding 11,000 records to /companies2 (half with creation attributes and half without). The above queries were able to retrieve 5500 matching records in about 4 seconds.

Update 3: If these queries are run frequently, segregating children of /companies into two categories based on the presence of creation could be beneficial. This way, the two segments can be read separately without relying heavily on queries.

Factory

Here is how the updated factory function would look like (the PLNKR has been modified to reflect this):

app.factory("CompaniesFactory",function($q, fbUrl){
  return function(hasCreation){
    var deferred = $q.defer();
    var ref = new Firebase(fbUrl+'/companies').orderByChild("creation");
    var query;
    if (hasCreation) {
      query = ref.startAt(!null);
    } else {
      query = ref.equalTo(null);
    }
    query.once("value", function(dataSnapshot){
      deferred.resolve(dataSnapshot.val());
    }, function (error) {
      deferred.reject(error);
    });
    return deferred.promise;
  }
});

It is indeed possible to call .on('child_added') on the returned dataSnapshot. Refer to DataSnapshot.ref() for more details.



Original response utilizing an additional parameter:

(Maintaining this for future reference)

An alternative approach involves introducing another parameter named hasCreation to the child elements of companies that possess the creation property, allowing for querying based on this criterion.

Data

  • The query would then be
    var ref = new Firebase(fbUrl+'/companies').orderByChild("hasCreation").equalTo(hasCreation);
    • If the hasCreation attribute in the query is null, it will return companies without a corresponding hasCreation child element.
    • If the hasCreation attribute in the query is true, it will return companies where hasCreation===true.
{
  "company1" : {
    "creation" : {
      "name" : "company1"
    },
    "hasCreation" : true
  },
  "company2" : {
    "name" : "company2"
  },
  "company3" : {
    "name" : "company3"
  },
  "company4" : {
    "creation" : {
      "name" : "company4"
    },
    "hasCreation" : true
  }
}

Rules

To include ".indexOn" : "hasCreation" in your rules, do as shown below:

  "so:29179389":{
    ".read" : true,
    ".write" : true,
    "companies" : {
      ".indexOn" : "hasCreation"
    }
  }

Companies Factory

app.factory("CompaniesFactory",function($q, fbUrl){
  return function(hasCreation){
    var deferred = $q.defer();
    if (!hasCreation) {
      hasCreation = null;
    }
    var ref = new Firebase(fbUrl+'/companies').orderByChild("hasCreation").equalTo(hasCreation);
    ref.once("value", function(dataSnapshot){
      deferred.resolve(dataSnapshot.val());
    });
    return deferred.promise;
  }
});

Controller

app.controller('HomeController',function($scope,fbUrl,CompaniesFactory) {
 $scope.getCompanies = function(hasCreation) {
  var companies = new CompaniesFactory(hasCreation).then(function(data){
     console.log(data);
     $scope.companies = data;
   });
 }
});

HTML

<body ng-app="sampleApp">
  <div ng-controller="HomeController">
    <button ng-click="getCompanies(true)">Find with creation</button>
    <button ng-click="getCompanies(false)">Find without creation</button>
    <h2>Companies:</h2>
    {{companies}}
  </div>
</body>

Answer №2

To address this issue, one strategy would be to check for the existence of the 'creation' key within the xxx.firebaseio.com/Application/companies/______/creation URL. By iterating over the array of companies using a loop, you can segregate them into two arrays using angular.forEach: one containing companies with 'creation', and the other without it.

I hope this solution proves useful :)

Additional Information:
For an alternative approach to this problem, please refer to this post:
Angularfire: how to query the values of a specific key in an array?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes? For instance: class Foo extends Bar { funcA() {} } class Bar { funcB() {} } const instanceFoo = new Foo(); getClass ...

convert a JSON object to an array using jQuery

Can anyone help me with converting an object into an array using jQuery? [["20"],["30"],["45"],["54"],["33"],["15"],["54"],["41"]] I am looking to achieve an array output like this: [20,30,45,54,33,15,54,41] Any suggestions on how to accomplish this? ...

Updating a button via ajax to execute a php script

Hello, I'm new to using JQuery AJAX and I could use some assistance with my code. My goal is to create a toggle effect where clicking the add button changes it to a delete button, and vice versa when the delete button is clicked. However, in my curren ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

What is the best way to retrieve the value of scope.postresult in JavaScript within my HTML code?

I have the following code in my controller.js file where I am retrieving the value of "postresult". $scope.open= function(post) { $scope.postresult = post; } In the HTML snippet below, I am loading a DISQUS thread and need to access the "postr ...

Functionality of the copy button

I have a Bootstrap code snippet that I want to use to create an address and add copy button functionality: <div class="modal fade" id="bitcoinModal" role="dialog"> <div class="modal-dialog modal-lg"> & ...

Sequential execution of multiple useState updates when an update triggers a re-render

Can you explain why the function setPeople is being executed after setFirstName, setEmail, and after the event handler has been exited? const [firstName, setFirstName] = useState(''); const [email, setEmail] = useState(''); const [peopl ...

Implement a vertex shader to transform a mesh's vertices without consideration of its current location

Looking to add movement to my meshes using a vertex shader, I've run into an issue where translating my meshes in the scene also affects the position of a sinus wave. The goal is to keep the sinus wave consistent across both meshes even when translati ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

IE8 is proving to be a major hurdle for the successful operation of AngularJS $http

Currently, I am faced with the challenge of creating an Angular application that needs to be compatible with IE8. However, I'm encountering difficulties in establishing a connection with the server. Surprisingly, whenever I attempt a $http.get, the en ...

d3js graphics, Opt for utilizing json strings over json file

My first experience with d3js was while utilizing the Line Chart Sample provided by this link. Despite successfully loading the data as seen in Firebug, the chart itself failed to display the data. I am unable to identify the issue and would greatly apprec ...

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

EJS Templates with Node.js: Embracing Dynamic Design

Is there a way to dynamically include templates in EJS without knowing the exact file name until runtime? The current EJS includes only allow for specifying the exact template name. Scenario: I have an article layout and the actual article content is stor ...

Utilizing request parameters within middleware that employs the 'createHandler' function from the 'graphql-http' package

I'm currently working on an Express server that uses GraphQL to handle HTTP requests. One of the key features of this Express server is the implementation of two crucial middlewares: app.use(authenticate); app.use('/graphql', createHandler ...

Retrieve the name of the page instead of the page number using PHP in combination with AJAX

I found a helpful tutorial on using AJAX to load content on a website. However, the tutorial uses generic page names like "page1, page2, page3, etc." and I want to use specific page names like "products, about, etc.". I've been working on the code in ...

Coding in PHP, JavaScript, and HTML allows builders

I am facing some difficulties in locating my specific question, so I will describe it here. Currently, I am working with an oracle database and integrating it into an HTML website using javascript and php. I have successfully displayed the php file, but th ...

Is it possible for CKEditor Plugin to extend allowedContent to elements further down the hierarchy, or is there a way to deactivate the MagicLine for specific elements?

I am in the process of developing a Drupal module that is inspired by the CKEditor Accordion Module, but with a twist of using Bootstrap 4 instead. The generated HTML markup by this module looks something like this: <section class="accordion" id="Acco ...

What is the proper usage of a jwt token?

I'm completely new to this and I've dedicated all my time to figuring out how to create a mechanism for generating JWT tokens. These tokens are necessary for identifying the 'signed in' status of users. I opted for FastAPI, and after s ...