Instantly share code, notes, and snippets.

What would you like to do?
Firebase: Creating data if it doesn't exist. This snippet creates a user only if it doesn't already exist.
function go() {
var userId = prompt('Username?', 'Guest');
var userData = { name: userId };
tryCreateUser(userId, userData);
function userCreated(userId, success) {
if (!success) {
alert('user ' + userId + ' already exists!');
} else {
alert('Successfully created ' + userId);
// Tries to set /users/<userId> to the specified data, but only
// if there's no data there already.
function tryCreateUser(userId, userData) {
var usersRef = new Firebase(USERS_LOCATION);
usersRef.child(userId).transaction(function(currentUserData) {
if (currentUserData === null)
return userData;
}, function(error, committed) {
userCreated(userId, committed);

This comment has been minimized.

ghost commented May 13, 2014

This is a comment


This comment has been minimized.

iamchriswick commented Nov 1, 2014

What if the user exists and I want to update the information?


This comment has been minimized.

curtisblackwell commented Jan 18, 2015

@iamchriswick in case you haven't already figured it out (or someone else has the same question), Firebase.transaction() is used to modify data and the first arg is the update function. That means if you leave out the if (currentUserData === null) conditional and just return userData, it would update existing info.


This comment has been minimized.

zipzit commented Jan 18, 2018

The link for Firebase.transaction() displays YOU'RE VIEWING THE LEGACY DOCS. THEY ARE DEPRECATED AS OF MAY 18, 2016. Its not exactly clear on what tools replace it..

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