6

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?

1 Answer 1

9

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');
    }
  });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Should that be if(data.$value != null) {, instead of the if(data.$value !== null) {?
I am using angularFire2. This check for object does not seem to work.
also i have to do this const user = this.af.database.object(`users/${login}`, { preserveSnapshot: true }); to make it to work and use data.val() to evaluate
you can also check with data.$exists(), it returns a boolean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.