简体   繁体   中英

Cloud Functions for Firebase - How to check whether a child exists?

I have database structure on Firebase like this:

- members
    |- -kSjJSDFjl2DFc
          |- nationality: Australian

- statistics-nationality
    |- American : 2

And "members" is being monitored for onWrite when "nationality-stats" will be updated.

I have this code to get the current nationality value of the new member, and then navigate to statistics-nationality, but I want to know whether a particular nationality node exists or not to choose either set or update action:

const currentNationality = event.data.current.child("nationality").val();
const statisticsNationality = event.data.ref.parent.parent.child('statistics-nationality');
let statisticsNationalityChild = statisticsNationality.child(currentNationality);

if (statisticsNationalityChild.exists()) { // No such an exists() method
   // update
} else {
   // create new nationality
}

However, no exists() method at this line:

statisticsNationalityChild.exists()

Please advise how to check whether a child exists or not? Thanks!

If I see your data structure correctly, then statistics-nationality is not part of the event data that triggered the function. In that case you'll need to try and read the data to determine if it exists:

const currentNationality = event.data.current.child("nationality").val();
const statisticsNationality = event.data.ref.parent.parent.child('statistics-nationality');
let statisticsNationalityChild = statisticsNationality.child(currentNationality);

statisticsNationalityChild.once("value").then((snapshot) => {
  if (snapshot.exists()) { 
    // update
  } else {
    // create new nationality
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM