How can I query and filter Firebase Realtime Database
The short answer: you can't. The long answer: use Google's new Firestore database or perform the filtering on the client manually. See this answer for other options.
query from firebase realtime database
br>As shown in the documentation on reading data, you can use get
to get the data at a path or for a query.
const myOffersRef = query(ref(db, 'allOffers/'), orderByChild('uid'), equalTo(user.uid));
get(myOffersRef).then((snapshot) => {
snapshot.forEach((child) => {
console.log(child.key, child.val().uid);
});
}).catch((error) => {
console.error(error);
});
Note that I also changed startAt
to equalTo
, as you likely only want the nodes that match the UID, not the slide of nodes starting from the first match (which is what startAt
does).
The forEach
is needed since a query can potentially have multiple results, so the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
How to read, write and query data in Firebase Realtime Database using Firebase SDK v9 (Modular)
Disclaimer: The v9 modular SDK is a beta release. The syntax may (or may not) change but I'll try to update the answer if any asap. Benefits of this upgrade can be found here.
The modular SDK cannot be used over CDN and you need to use npm or yarn for the time being. I've tested this in a Vue web-app.
1. Initialize the Firebase App:
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "<api-key>",
authDomain: "<project-id>.firebaseapp.com",
databaseURL: "https://<project-id>.firebaseio.com",
projectId: "<project-id>",
storageBucket: "<project-id>.appspot.com",
messagingSenderId: "0000000000",
appId: "<app-id>",
}
const app = initializeApp(firebaseConfig)
2. Create a Database Instance and Reference:
import { getDatabase, ref } from "firebase/database"
const db = getDatabase(app) // <-- Pass in the initialized app
//Creating the reference (The path in db you are trying to read/write/update)
const dbRef = ref("/users")
3. Read Operation and Listeners:
You need to use get()
method to retrieve data which accepts a query as parameter. If you are simply reading the data without any sorting or filtering, just pass the reference created above in the query()
. (Note: Passing the reference directly in get() works in this case)
import { get, query, onValue } from "firebase/database"
const usersSnapshot = await get(query(dbRef)) //This should get the whole users node from db.
//To add a listener you can use the onValue() method like,
onValue(query(dbRef), snapshot => {
console.log(snapshot.val())
})
//
In v8, the syntax for events looks like .on("event_name")
. In v9, all events are a method which can be used this way:
import { onChildAdded, onChildChanged, onChildRemoved } from "firebase/database"
onChildAdded(query(dbRef), (snapshot) => {
console.log("child added");
console.log(snapshot.val()); // Logs newly added child
});
onChildChanged(query(dbRef), (snapshot) => {
console.log("child changed")
console.log(snapshot.val()); // Logs updated value of changed child
});
onChildRemoved(query(dbRef), (snapshot) => {
console.log("child removed");
console.log(snapshot.val()); // Logs value of removed child
});
4. Writing Data:
// You maybe have figured out the upgrade trend ¯\_(ツ)_/¯
import { set, update } from "firebase/database"
const newUserName = "user1122"
const userRef = ref(`users/${newUserName}`)
await set(userRef, {name: newUserName, age: 11})
await update(userRef, {age: 12})
5. Working with lists:
This is best part and it now kind of feels similar to adding stages in a MongoDB Aggregation.
import { query, orderByChild, orderByValue, orderByKey, limitToLast } from "firebase/database"
//Example: getting 3 youngest users from the db
const usersSnapshot = await get(query(dbRef, ...[orderByChild("age"), limitToFirst(3)]))
The first parameter in the query()
is the Database Reference and all following parameters are QueryConstraints and can be either of these methods: 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';
. You can pass them as individual parameters instead of using spread operator as I've used.
I've found no issues using the modular SDK so far. Just make sure you've imported all things which are needed.
PS: Just in-case if you use Vue, React or any framework with hot-reload when developing, you might encounter the "Firebase App named '[DEFAULT]' already exists (app/duplicate-app)" error. Checking if firebase.apps.length
is 0 helps and that's done this way in modular SDK:
import { getApps, initializeApp } from "firebase/app"
if (!getApps().length) initializeApp(firebaseConfig)
firebase 9 query realtime database for key
You can keep adding those QueryConstraints in query():
const db = getDatabase();
const dbRef = ref(db, "/Countries")
const queryConstraints = [orderByChild("name"), equalTo('value')]
const dataSnapshot = await get(query(dbRef, ...queryConstraints))
Also checkout:
- How to read, write and query data in Firebase Realtime Database using Firebase SDK v9 (Modular)
- Working with lists on web
Use query data from Firebase Realtime DB as input for another function
br>The on
method keeps an open listener to the event that can be called repeatedly, so it doesn't return a promise (since a promise can only resolve once). So the await ref.orderByChild....on('child_added'...
in your code doesn't do anything, which probably explains the problem.
To properly solve this problem, use once('value', ...
and don't combine await
and callbacks.
async function queryandgeturls() {
// make the query to the firebase realtimeDB
const results = await ref.orderByChild('timestamp_start').startAt(timestamp1).endAt(timestamp2).once('value');
results.forEach((snapshot) => {
lista.push(snapshot.val().name);
});
...
Related Topics
Updating Progress Dialog in Activity from Asynctask
Read the Package Name of an Android APK
How to Enable Logging for Apache Commons Httpclient on Android
Android How to Display 2 Listviews in One Activity One After the Other
How to Integrate Opencv Manager in Android App
How to Call a Method in Another Activity from Activity
Get Center Visible Item of Recycleview When Scrolling
Setuservisiblehint Called Before Oncreateview in Fragment
Animating Markers on Google Maps V2
Set Limit on the Datepickerdialog in Android
Kill Another Application on Android
How to Encrypt File from Sd Card Using Aes in Android
Enable/Disable Zoom in Android Webview
Android Boot_Completed Not Received When Application Is Closed
Android - Application (Apk) Maximum Size
Some Androids Apps Won't Connect Through Fiddler