简体   繁体   中英

Checking with Cloud Function if a database node exists in Firebase Realtime Database

I have a onUpdate Cloud Function and I need to check if a database node exists.

For my the ideal way to do it would be:

exports.watchTeamMemberUpdates = functions.database
  .ref('/teams/{teamName}')
  .onUpdate((change) => {
     if (!change.before.exists()) {
       console.log('exists error');
       return null;
     }
});

But it requires a snapshot and i'm giving it a promise.

Is it possible to check if the file exists with the promise in any way?

Also is there a better way to make snapshots other than .once.then?

I make the assumption that by writing "I need to check if a file exists" you mean checking if a database node exists (ie the team member saved under team name). I've taken the liberty to modify your question title and content accordingly.


Note that if you want to detect if the team member didn't exist with an onUpdate() trigger, you will not succeed , because this Cloud Function will only be triggered if the node existed before , since we watch for updates (not for creation).

So you should probably use an onWrite() trigger. Below is the code for the two types of trigger. I would suggest you try several writes and updates in your database (after having deployed theses two functions, of course) and look what is printed to the Cloud Function log.

exports.watchTeamMemberUpdates = functions.database
  .ref('/teams/{teamName}')
  .onUpdate((change, context) => {
    if (!change.before.exists()) {
      console.log('watchTeamMemberUpdates: exists error');
      return null;
    } else {
      console.log('watchTeamMemberUpdates: Team member exists');
      return null;
    }
  });

exports.watchTeamMemberWrites = functions.database
  .ref('/teams/{teamName}')
  .onWrite((change, context) => {
    if (!change.before.exists()) {
      console.log('watchTeamMemberWrites: exists error');
      return null;
    } else {
      console.log('watchTeamMemberWrites: Team member exists');
      return null;
    }
  });

PS: Note that the handler to be passed to the onUpdate(handler) method is a function with two arguments, see https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate . However the second is optional. This is the same with the onWrite(handler) method.

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