Home > Blockchain >  firebase 9 query realtime database for key
firebase 9 query realtime database for key

Time:11-30

I want to query realtime database using firebase 9, I previously used admin sdk, i have this example that works but I am having problems adjusting to version 9. I cant find any solid examples on how to use those modular methods to query. Any examples would be appreciated.

version 8

return admin
    .database()
    .ref("Countries")
    .orderByChild("name")
    .equalTo(query)
    .once("value")
    .then((data) => {
      if (data.exists()) {
        const obj = Object.keys(data.val())[0];
        const country = data.val()[obj];

        return country;
      } else {
        return null;
      }
    })
    .catch((error) => {
      console.log("error finding country name", error);
      return null;
    });

what I have tried

const { getDatabase, child, get, ref ,orderByChild,equalTo} = require("firebase/database");

    const toFind = "USA"

    const dbRef = ref(getDatabase());
    const query = await get(child(dbRef, `countries`));
    //orderByChild

    //equalTo

UPDATED SOLUTION:

 const dbRef = ref(db, "/countries");

    const queryConstraints = [orderByChild("name"), equalTo(name)];

    const country = await get(query(dbRef, ...queryConstraints));

    if (country.exists()) {
      console.log("found by name", country.val());
    } else {
      console.log("No data available");
      return null;
    }
  } catch (error) {
    console.log("====================================");
    console.log("error getting country", error);
    console.log("====================================");
  }

CodePudding user response:

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:

  • Related