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).
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.