简体   繁体   中英

Checking data in deep array with includes (Firebase retrieve data JS)

So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.

Also, I am wondering if this is the right way to retrieve data from the database:

Main.js

function writeUserData() {

    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;

    firebase.database().ref('/aanmeldingen/').push({
      username: name,
      email: email,
    });

    var dbRef = firebase.database().ref().child('/aanmeldingen/');
    dbRef.on('value', snapshot => {
      const snap = snapshot.val();
      const array = [];

      array.push(snap);
      console.log(array);

      const res = array.includes(email);
      console.log(res);
      console.log(email);
    });
 }

Output in console

在此处输入图片说明

As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info@webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.

I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.

function ifEmailExist(arr,email){
    var _t = 0;
    for(var x in arr){
        for(var y in arr[x]){
            if(arr[x][y].email){
                if(arr[x][y] === email){
                    _t++;
                }
            }
        }
    }
    return _t;
}

Usage:

if(ifEmailExist(arr,"info@webpack.com") > 0){
   //do stuff
}

You should use child_added instead of value . Whenever a new node is added in database, child_added will trigger and then you can take action on the data.

var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
  var username = snapshot.val().username;
  var email = snapshot.val().email;

  console.log(username);
  console.log(email);
});

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