Bruno Justino Praciano
Bruno Justino Praciano

Reputation: 552

How to verify if data exist in Firebase

I'm having a problem saving data to firebase, because my data only updates the data already in the database, it does not insert new data. That is when I create a new user and it solves an exercise when trying to fetch this data in the firebase it returns me this error.

FIREBASE WARNING: Exception was thrown by user callback. TypeError: Can not convert undefined or null to object.

function writeUserData(userId, data) {
    var key    = Object.keys(data)[0];
    var values = Object.values(data)[0];
    console.log(values);

    firebase.database().ref('users/' + userId + '/' + jsData.topicId + '/' + key).set({
            topic_log: values
        });
    }

Upvotes: 1

Views: 1306

Answers (2)

Lesley
Lesley

Reputation: 1395

You can use the exists() method of the data snapshot to check for data.

For example:

var userRef = firebase.database().ref('users/' + userId);
userRef.once('value', function(snapshot) {
    if (snapshot.exists){
        console.log('user exists');
    }
});

Upvotes: 1

Bara' ayyash
Bara' ayyash

Reputation: 1925

take a look to this code right here :

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);
  });
}

Upvotes: 2

Related Questions