Get the auto-generated id - Firebase - javascript

I'm trying to retrieve the id of the element that I inserted in the database with .key. However, it returns the user value instead of the auto-generated id.
How can I get the auto-generated id ?
var mainText = document.getElementById("main-text");
var emailText = document.getElementById("emailtxt");
var prenom = document.getElementById("prenomtxt");
var submitBtn = document.getElementById("submitBtn");
var heading = document.getElementById("heading");
var firebaseHeadingref = firebase.database().ref().child("titre");
firebaseHeadingref.on('value', function(datasnapchot){
heading.innerText = datasnapchot.val();
})
function submitClick(){
var firebaseref = firebase.database().ref();
var messageText = mainText.value;
var txtmail = emailText.value;
var prenomtxt = prenom.value;
if(messageText == "" || txtmail == "" || prenomtxt == ""){
alert("Tous les champs doivent être remplis");
return;
}
firebaseref.child("user").push().set({name : messageText, prenom:prenomtxt ,email : txtmail});
var f = firebase.database().ref().child("user").orderByChild("email").equalTo(txtmail);
// firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
//
// console.log(pushed_user.key);
//
// });
f.on("value", function(datasnapchot){
var id = datasnapchot.val();
console.log(id);
});
// location.reload();
}
There is a console notice:
It looks like you're using the development build of the Firebase J5 SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use. For the CON builds, these are available in the following manner (replace ‹PACKAGE> with the name of a component - 1.8. auth, database, etc):
https://www.gstatic.com/firebasejs/5.0.0/firebase-‹PACKAGE›.js

Try calling it like a function:
var id = datasnapchot.key();

When you push an element you can directly retrieve the auto generated ID without having to call a listener.
firebaseref.child("user").push({name: messageText, prenom:prenomtxt, email: txtmail}).then(pushed_user => {
console.log(pushed_user.key);
});
You can find another example here.

var newPostKey = firebaseref.child("user").push().set({name : messageText,prenom:prenomtxt ,email : txtmail}).key;
"newPostKey" will be your key

Try the following:
var ref = firebase.database().ref("users");
ref.push().on("value", function(snapshot) { snapshot.forEach(function(childSnapshot) {
var id = childSnapshot.key();
console.log(childSnapshot);
});
});
You need to loop using forEach and then you will be able to retrieve the push key using key()

This worked for me
var id = datasnapchot.key;
Use datasnapchot.key instead of datasnapchot.key()

Related

Trying to delete the value of key for web application through firebase

what would make this work so that when the user types the correct tobedeleted value, the database deletes corresponding key with entered name?
function remove(){
var nameInput=document.getElementById("nameInput");
var database = firebase.database();
var tobedeleted = document.getElementById("tobedeleted").value;
var rootRef = database.ref("information");
var query = rootRef.orderByKey();
//gets generated keys
query.once("value",function(snapshot){
snapshot.forEach(function(childSnapshot){
var key = childSnapshot.key;
var val = childSnapshot.val();
console.log(val.name);
console.log(tobedeleted);
if (val.name===tobedeleted /*edited from val.name.equalTo(tobedeleted)*/)
{
rootRef.child("information/"+key).remove();
}
});
});
Found the solution: just changed ("information/"+key) to (key)

Fetching data from firebase web

I am trying to fetch the data for website using java script.
Problem I am getting is that I am unable to get the key of
Users-->Customers-->Key-->(name, phone).
I am unable to find a syntax of it
Code I am trying is
var fireheading = document.getElementById("fireHeading");
var firebaseHeadingRef = firebase.database().ref().child("Users").child("Customers").child(uid).child("name");
firebaseHeadingRef.on('value', function(datasnapShot){
fireHeading.innerText = datasnapShot.val();
});
To get data from Firebase in javascript, you would do this:
var fireHeading = document.getElementById("fireHeading");
// "key" is the customer key
var ref = firebase.database().ref("Users/Customers/" + key);
ref.once("value", function(snapshot){
// Contains all data from Firebase
var data = snapshot.val();
// Has customer name
var customerName = data.Name;
// Has customer phone
var customerPhone = data.Phone;
// Append data to view
fireHeading.innerText = customerName;
});
This should work.

node.js and ejs variable not showing at page refresh

I'm trying to pass variable from js to .ejs template file. The values are coming at page first opening but not showing at refresh page. When I log variables, they are seem in console at every refresh.
ejs:
<input type="text" value="<%= userfb.testTarget %>" data-min="<%= userfb.testMin %>" data-max="<%= userfb.testMax %>" data-fgcolor="#157fa2" class="dial ringtarget">
app.js
var query = firebase.database().ref('/doctors/patients/' + request.id + "/testResults");
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var resultData = childSnapshot.val();
var testid= resultData.testid;
console.log("testid:"+testid);
//Setting Test Results
// Loop through users in order with the forEach() method. The callback
// provided to forEach() will be called synchronously with a DataSnapshot
// for each child:
var childData = childSnapshot.val();
console.log(childData.testResultValues);
var testResultValues =[];
for (i in childData.testResultValues) {
testResultValues.push(childData.testResultValues[i].value);
}
userfb.testResultValues=testResultValues;
console.log(testResultValues);
//Getting test informations
var testquery = firebase.database().ref('/doctors/tests').orderByChild("testID").equalTo(testid);
testquery.once("value")
.then(function(snapshot2) {
snapshot2.forEach(function(snapshot2) {
var testData = snapshot2.val();
userfb.testName=testData.testName;
userfb.testMax=testData.limitValues.max;
userfb.testMin=testData.limitValues.min;
userfb.testTarget=testData.normalValues.Female;
console.log("testmax:"+userfb.testMax);
});
});
});
});
Solution:
I divided the return values (as userfb and testInformations) for each firebase query and now working with refresh page.
var query = firebase.database().ref('/doctors/patients/' + request.id + "/testResults");
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var resultData = childSnapshot.val();
var testid= resultData.testid;
console.log("testid:"+testid);
//Setting Test Results
// Loop through users in order with the forEach() method. The callback
// provided to forEach() will be called synchronously with a DataSnapshot
// for each child:
var childData = childSnapshot.val();
console.log(childData.testResultValues);
var testResultValues =[];
for (i in childData.testResultValues) {
testResultValues.push(childData.testResultValues[i].value);
}
userfb.testResultValues=testResultValues;
console.log(testResultValues);
//Getting test informations
var testquery = firebase.database().ref('/doctors/tests').orderByChild("testID").equalTo(testid);
testquery.once("value")
.then(function(snapshot2) {
testInformations = snapshot2.val()
snapshot2.forEach(function(snapshot2) {
var testData = snapshot2.val();
testInformations.testName=testData.testName;
testInformations.testMax=testData.limitValues.max;
testInformations.testMin=testData.limitValues.min;
testInformations.testTarget=testData.normalValues.Female;
console.log("testmax:"+testInformations.testMax);
});
});
});
});

Get an unknown key name from Firebase function database trigger

I'm new to Firebase functions and trying to understand how to get a certain key from the database .onCreate trigger. Here is an example:
exports.createUserRoundData =
functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var eventData = event.data.val();
var userKey = event.params.user_key;
var itemKey = eventData.items; // This returns an object
});
The structure is:
players > user_key > items > item_key > data
In the above scenario how can I retrieve the item_key?
Yes you can,
You need something like this :
exports.createUserRoundData = functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var userKey = event.params.user_key; // Get user key parameter
var eventSnapshot = event.data; // Get player data
var itemsSnapshot = eventSnapshot.child('items'); // Get items data
itemsSnapshot.forEach(function(itemSnapshot) { // For each item
var itemKey = itemSnapshot.key; // Get item key
var itemData = itemSnapshot.val(); // Get item data
});
});
Here the Firebase Cloud Functions documentation.

Data not updating in Firebase and Ionic

I am new to Ionic / Firebase and I try to update fields via a form. Everything works, no error, all console log show up what needed but the data are not being updated in the database.
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
function writeUserData(name, description) {
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
}
$state.go("tab.account");
});
Any idea ? Or maybe a better method to simply update firebase's database via a form when the user is logged in ?
Seems you didn't really don't know the real significance/uses of function yet about when to use it
Well it's because you wrap it inside writeUserData and which is you didn't event execute/call this function
Also function writeUserData isn't necessary in this situation
so remove function it
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
});
You just transfer $state.go("tab.account"); to receiveNewData
Edited
To be able to catch the changes just call add child_added event listener inside 'accounts/' + userId
function receiveNewData() {
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}

Categories