简体   繁体   中英

Detect if an email already exists in firebase

I have the following in my FireBase database:

Users
 -VCVVsqwws_QSds2ADC1
    email: 
      "lo@aol.com"
 -VCVxCaQ_dSwWBC21AB4
    email: 
      "asdasasd@aaa.com"

and then the lines in my .js file:

firebase.initializeApp(config);
var register = firebase.database().ref("Users");

How can I check if Users already contains an email before pushing it to Users ? I tried to follow https://gist.github.com/anantn/4323949 but the browser says cannot instantiate Firebase (new Firebase) even though everything is imported and included.

You can use the following code:

var register = firebase.database().ref("Users/{{userId}}");

register.once('value', function(snapshot) {
   if(snapshot.val().hasOwnProperty('email')) {
     console.log("Email exist.");
   }
   else {
     console.log("Email not exist.");
     /* Code to push email to the specific user */
   }
});

You can also use the following code (trigger warning: es6) if you need to check only one user really fast:

firebase.database().ref(`Users/${userId}`)once('value').then(snapshot => {
   if(snapshot.val().hasOwnProperty('email')) {
     console.log("Email exists.");
   }
   else {
     console.log("Email doesn't exist.");
     /* Code to push email to the specific user */
   }
});

Note that ti2005's snippet works perfectly well but it will load all users and that process will get slower as your database grows.

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