Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I query Firebase Realtime Database by value when it is only a list of key:values?

I have a few collections in a Firebase Realtime Database that are structured like this::

SomeCollectionName {
  randomKey1: userId1,
  randomKey2: userId2,
  randomKey3: userId3,
  randomKey4: userId1,
  randomKey5: userId1
}

I want to query SomeCollectionName where the values are equal to userId1, but am having a hard time figuring out how to get those values without knowing the key, and not even having any child nodes to perform an orderByChild on.

I’m working in a backend environment in pure NodeJS/JavaScript (no Angular).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This seems like it should be a simple task, but I am stuck.

>Solution :

You can use the orderByValue method to query the values in your Firebase Realtime Database. Here’s how you can

const admin = require('firebase-admin');
const db = admin.database();

const ref = db.ref('SomeCollectionName'); 
ref.orderByValue().equalTo('userId1').on('value', function(snapshot) {
  console.log(snapshot.key);
});

This code will return all the keys where the value is equal to ‘userId1’. The on() method is used to listen for changes to the data at the specified location. The snapshot parameter contains a snapshot of the data at the location and can be used to access the data. You can replace the console.log(snapshot.key) with your desired code to process the result.

Note that you need to initialize Firebase Admin SDK before using the above code. You can follow the instructions in the Firebase documentation to do this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading