Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Angularfire2 checking if user exists in the database

I have a database with 2 objects. It looks like this:

users
    - KEY
        login: "xexe"
        password: "123"

    - KEY
        login: "dede"
        password: "123"

Now I'm checking if user exists in the database

  constructor(private af: AngularFire) {
    this.users = af.database.list('/users');
  }

  registerUser(login: string, password: string) {
    this.af.database.list('/users', {
      query: {
        orderByChild: 'login',
        equalTo: login
      }
    }).subscribe(response => {
      if(response.length === 0) {
        console.log("User does not exist");
        //here i will add a user
      } else {
        console.log("Users exists");
      }
    })
  }

What's the problem?

Let's try to register a user with "dede" login (user should exists)

When I click a submit button first time, the console shows: Users exists -> well, that's good.

The problem is when I click the submit the second time (without refreshing webpage)

Then console.log shows me two messages

User does not exist
User exists

and that would add a new user what shouldn't be done. Why the second time the subscribe function iterate through every row? How to fix it?

like image 200
elzoy Avatar asked Jul 17 '16 14:07

elzoy


1 Answers

Rather than use a query, you can structure your data to use the login property as they KEY.

{
  "users": {
    "dede": {
      "login": "dede",
      "password": "Do not store passwords :)"
    },
    "xexe": {
      "login": "xexe"
    }
  }
}

Now you can create a reference to this location and check if the object exists.

registerUser(login: string, password: string) {
  const user = this.af.database.object(`users/${login}`);
  user.subscribe(data => {
    if(data.$value !== null) {
      console.log('User does not exist');
    } else {
      console.log('User does exist');
    }
  });
}
like image 91
David East Avatar answered Oct 18 '22 01:10

David East