Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Firebase: Detecting if data exists. This snippet detects if a user ID is already taken
function go() {
var userId = prompt('Username?', 'Guest');
checkIfUserExists(userId);
}
var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
function userExistsCallback(userId, exists) {
if (exists) {
alert('user ' + userId + ' exists!');
} else {
alert('user ' + userId + ' does not exist!');
}
}
// Tests to see if /users/<userId> has any data.
function checkIfUserExists(userId) {
var usersRef = new Firebase(USERS_LOCATION);
usersRef.child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userExistsCallback(userId, exists);
});
}
@max-holland

This comment has been minimized.

Copy link

@max-holland max-holland commented Jul 11, 2013

Nice dude!

@dustinlarimer

This comment has been minimized.

Copy link

@dustinlarimer dustinlarimer commented Sep 20, 2013

This is great, thank you!

@bhavs

This comment has been minimized.

Copy link

@bhavs bhavs commented Oct 15, 2013

any idea how this can be done using Java? I am using firebase backend for an android app

@bcherny

This comment has been minimized.

Copy link

@bcherny bcherny commented Nov 28, 2013

+1

@douglaslyon

This comment has been minimized.

Copy link

@douglaslyon douglaslyon commented Jan 1, 2014

We really need java examples

@realgt

This comment has been minimized.

Copy link

@realgt realgt commented Feb 3, 2014

Here is how you would check it in Java

Firebase userRef= new Firebase(USERS_LOCATION);
userRef.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.getValue() !== null) {
            //user exists, do something
        } else {
            //user does not exist, do something else
        }
    }
    @Override
    public void onCancelled(FirebaseError arg0) {
    }
});
@visalig

This comment has been minimized.

Copy link

@visalig visalig commented Dec 10, 2014

Firebase userRef= new Firebase(USERS_LOCATION);
userRef.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
@override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.getValue() !== null) {
//user exists, do something
} else {
//user does not exist, do something else
}
}
@override
public void onCancelled(FirebaseError arg0) {
}
});

Single user this is ok, but how to compare the more than one user?

I try below type thats not working can u anyone give me a idea for this
Firebase ref= new Firebase(USERS_LOCATION);
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.getValue() !== null) {
//user exists, do something
} else {
//user does not exist, do something else
}
}
@override
public void onCancelled(FirebaseError arg0) {
}
});

@visalig

This comment has been minimized.

Copy link

@visalig visalig commented Dec 10, 2014

above one is working for username or email or phone only check to find the user already exit or not, but how to i compare the more than one user at a same time to find the user exit or not. i used this
Firebase ref= new Firebase(USERS_LOCATION);
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.getValue() !== null) {
//user exists, do something
} else {
//user does not exist, do something else
}
}
@override
public void onCancelled(FirebaseError arg0) {
}
});
way but its always going to already exit method only, anyone can explain. how to do that?

@biskalero78

This comment has been minimized.

Copy link

@biskalero78 biskalero78 commented Feb 3, 2015

That is very strange, when I try to do that in my own application , it does not even go into the function only if data exists which I am tearing hair out because of it.

@bwilytsch

This comment has been minimized.

Copy link

@bwilytsch bwilytsch commented Apr 24, 2015

Awesome. Thanks a lot!

@rawrmaan

This comment has been minimized.

Copy link

@rawrmaan rawrmaan commented May 15, 2015

This is awful.

@champi0ne

This comment has been minimized.

Copy link

@champi0ne champi0ne commented Jun 16, 2015

This is definitely an anti-pattern described in the firebase docs.

@canopii

This comment has been minimized.

Copy link

@canopii canopii commented Jun 22, 2015

how to check for more then one value lets say Name: John Surname:Smith how do I check if both exist must i use a two methods?

@lgomez

This comment has been minimized.

Copy link

@lgomez lgomez commented Jun 23, 2015

you probably don't need this but I figured I'd share it. Just feels a bit cleaner to me:

// The ideantifier in the collection.
var uid = 2;
// the data for the object being created/updated.
var user = {
    name: "Luis",
    twitter: "@luisgo"
};
// attempt to get the child in the collection by uid.
db.child('users').child(uid).once('value', function(snapshot){
    // if data exists
    if (snapshot.exists()) {
        // get the ref (in this case /users/2) and update its contents
        snapshot.ref().update(user);
    } else {
        // data does not exist so we wrap the data in an object with
        // a member named after the uid so we can pass it as an update
        // to the parent.
        var payload = {};
            payload[uid] = user;
        // get the ref's parent and call update on it.
        snapshot.ref().parent().update(payload);
    }
});
@cheenbabes

This comment has been minimized.

Copy link

@cheenbabes cheenbabes commented Sep 8, 2015

@lgomez that is brilliant! You saved me so much time.

@iheartkode

This comment has been minimized.

Copy link

@iheartkode iheartkode commented Jan 27, 2016

+1

@tumaponchard16

This comment has been minimized.

Copy link

@tumaponchard16 tumaponchard16 commented Feb 19, 2016

Can anyone has an idea on how to do it in Laravel?

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Mar 4, 2016

nice

@Abdul007Malik

This comment has been minimized.

Copy link

@Abdul007Malik Abdul007Malik commented Apr 26, 2016

I am making chat application using java, "https://github.com/Abdul007Malik/Conversa.git", I am confused and cannot progress further help me if you can, my questions:

  1. if I know the auth.getUID of others can i modify there data or firebase have different mechanism to check authentication.
  2. how can I send the invitation(inviting to join the group) to friends if i know there phone numbers but dont know there particular userid.
@sebasj14

This comment has been minimized.

Copy link

@sebasj14 sebasj14 commented Apr 30, 2016

This was just perfect. Thank you!

@davidgilbertson

This comment has been minimized.

Copy link

@davidgilbertson davidgilbertson commented May 10, 2016

A promise based version (where db is a Firebase ref)

export function checkIfUserExists(authData) {
  return db
    .child('users')
    .child(authData.uid)
    .once('value')
    .then(dataSnapshot => {
      return Promise.resolve({
        authData,
        userExists: dataSnapshot.exists(),
      });
    });
}

Which would be called like so:

  db.authWithOAuthPopup(provider)
    .then(checkIfUserExists)
    .then(({authData, userExists}) => {
      if (userExists) {
        // update user
      } else {
        // go create a user
      }
    })
    .catch(err => {
      console.warn('Error signing in.', err);
    });

Gist: https://gist.github.com/davidgilbertson/52a72f7c5e35502127e5848a8bf881b2

@amanuel2

This comment has been minimized.

Copy link

@amanuel2 amanuel2 commented Jun 4, 2016

Thanks a lot sir. Helped me construct my own idea

@samyoungnyc

This comment has been minimized.

Copy link

@samyoungnyc samyoungnyc commented Jun 20, 2016

has anyone figured this out using Python? I'm using the following library: https://pypi.python.org/pypi/python-firebase/1.2

@amirshahzadmcs

This comment has been minimized.

Copy link

@amirshahzadmcs amirshahzadmcs commented Jun 21, 2016

Please any body can tell me that i have request record in firebase . i want to get spesific user which userId is 91 how i can access this user by query on firebase

{
"request" :
{
"123" :
{
"userId" : "90",
"name" : "mary"
},
"124" :
{
"userId" : "91",
"name" : "johan"
},
"124" :
{
"userId" : "92",
"name" : "maikal"
}
}
}

@sudikrt

This comment has been minimized.

Copy link

@sudikrt sudikrt commented Jul 15, 2016

How to retrieve the user email using the user id (client id)?

@j-garin

This comment has been minimized.

Copy link

@j-garin j-garin commented Aug 4, 2016

sudikrt, create a table with names and emails and add data to it after user has registered. then you will be able to search for records by email or id.

@ayudh37

This comment has been minimized.

Copy link

@ayudh37 ayudh37 commented Nov 3, 2016

The crux: var exists = (snapshot.val() !== null);

@ayoola-solomon

This comment has been minimized.

Copy link

@ayoola-solomon ayoola-solomon commented Jun 20, 2017

if you want to listen on a node. You can change the implementation to the snippet below.

  const checkIfUserExists = (userId) => {
    const usersRef = new Firebase(USERS_LOCATION);
    usersRef.child(userId).on('value', (snap) => {
    const exists = (snap.val() !== null);
    userExistsCallback(userId, exists);
   });
 }
@caionovalins

This comment has been minimized.

Copy link

@caionovalins caionovalins commented Jun 23, 2017

didn't know about the once() method. thanks 👍

@l-bimba

This comment has been minimized.

Copy link

@l-bimba l-bimba commented Jun 26, 2017

Can you do this in swift?

@guilhermemauro

This comment has been minimized.

Copy link

@guilhermemauro guilhermemauro commented Jul 22, 2017

Nice!

@Sowmayjain

This comment has been minimized.

Copy link

@Sowmayjain Sowmayjain commented Jul 23, 2017

+2

@Sunitadaffodil

This comment has been minimized.

Copy link

@Sunitadaffodil Sunitadaffodil commented Feb 14, 2019

I am making chat application using java, "https://github.com/Abdul007Malik/Conversa.git", I am confused and cannot progress further help me if you can, my questions:

  1. if I know the auth.getUID of others can i modify there data or firebase have different mechanism to check authentication.
  2. how can I send the invitation(inviting to join the group) to friends if i know there phone numbers but dont know there particular userid.

Did you find any solution for this. I am facing same issue where I know email id but not user id

@tayouthae

This comment has been minimized.

Copy link

@tayouthae tayouthae commented Jan 24, 2020

Can you give us python examples??

@lohriialo

This comment has been minimized.

@bloodysysy73

This comment has been minimized.

Copy link

@bloodysysy73 bloodysysy73 commented Dec 23, 2020

thank's man, very helpful =)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment