2

I have a firebase database as described below:

"users" : {
    "USER1_ID" : {
      "email" : "user1@xxxx.com",
      "last_connection" : "dd-mm-yyyy",
      "name" : "Mr User1",

    },
    "USER2_ID" : {
      "email" : "user2@yyyy.com",
      "last_connection" : "dd-mm-yyyy",
      "name" : "Mr user2"
    }
  }

How do I translate the following SQL query to an angular2/angularfire2 query:

SELECT COUNT(USER_ID) from USERS WHERE USER_ID = UID;

The aim of this query is to determine if a record exists. I am thinking about the below solution:

existsUser(UID: string): boolean {
  this.af.database.list(`/users/${UID}`)
    .subscribe ((user) => {
      if (user.length == 0) {
        return false;
      }
    });
  return true;
}

Is this the fastest way to determine if a record exists?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
da45
  • 311
  • 1
  • 3
  • 13
  • The Firebase Database does not have a built-in count operator. See http://stackoverflow.com/questions/38443421/how-to-get-size-of-an-element-list-in-firebase-without-get-it-all – Frank van Puffelen Dec 06 '16 at 09:41
  • 1
    Have you tried to check `this.af.database.object('/users/${UID}')` instead of `list`? – crash Dec 06 '16 at 10:23

1 Answers1

1

Angularfire2 has $exists() method that can be used as follows to determine if a firebase record exists:

this.af.database.object(`/users/${UID}`).subscribe((user) => {
    return user.$exists();
});
jgithaiga
  • 134
  • 6