I'm trying to write some code that will create/insert user data into my Firebase app (web-based).
I want to do this after the user authenticates with their email & password (that part is working correctly).
But I'm having some trouble with storing the user's ID, username, email, age and profile picture in the Firebase database.
This is the database structure I'm aiming for:
MyAppReference
|
|___users
|
|_____UID
|___username
|___email
|___age
|___profile_picture
When the User ID (UID) is generated after the user signs up with their email & password, I want to save it as the user's unique identifier inside the "users" field. Then inside their UID I want to store their username, email, age and profile_picture. But I don't know how to create the parent (UID) and children in the same piece of code.
This is my current attempt:
function insertUserDetails() {
var useremail = "[email protected]";
var userpassword = document.getElementById("passwordfield").innerHTML;
firebase.auth().createUserWithEmailAndPassword(useremail, userpassword).then(function(user) {
console.log("User is authenticated, attempting to enter the user data now...");
// Define variables for sending to database:
var username = "JohnDoe";
var userId = user.uid;
var age = "50";
var profile_picture = "http://zntent.com/wp-content/uploads/2016/03/will-ferrell-film.jpg";
function writeUserData(userId, username, useremail, age, profile_picture) {
// Attempting to create the parent "UID" (child of "users") here:
function addStore(){
var rootRef = firebase.database().ref();
var storesRef = rootRef.child('MyAppReference/users');
var newStoreRef = storesRef.push();
newStoreRef.set({
"UID": userId,
});
}
// Attempting to create/insert user data under that user's UID:
firebase.database().ref('users/' + userId).set({
username: username,
email: email,
age: age,
profile_picture : profile_picture
});
}
}, function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
Console.log("There was an error: " + errorCode + "." + errorMessage);
// ...
});
}
This isn't working, but I'm not receiving any errors in the console when I test it. The user is being authenticated correctly and their username and user ID appear in the Firebase console, but there's no trace of them in the Database.
What is the proper method for doing this? I'm used to SQL and this is my first time using a noSQL database, so maybe I have things completely wrong?
Any help fixing this would be really appreciated. Thank you in advance!