I'm working with Firebase realtime database and I want to retrieve an array data:
Data:
And my function:
function traerUsuarios(firebase)
{
var ref = firebase.database().ref().child('/Usuario');
console.log(ref)
ref.once('value', function (snap) {
snap.forEach(function (item) {
var itemVal = item.val();
console.log(itemVal);
});
});
}
But the result:
Show me object but no de for of the items
What im doing wrong?
Each item in your for loop are the children of Usario. Each of these children (from your picture 056BN.., CQL.., and E4ll) have an object as their value (hence why they have a + next to them in the database).
So when you say item.val() you're getting the value of each one of those children, which is their corresponding object (The data you see when you click the + in the database.
Thanks to #MarksCode , I fixed the function with data refs:
function traerUsuarios(firebase) { var key;
var starCountRef;
var usuarios=new Array();
// var ref = firebase.database().ref().child('/Usuario');
var query = firebase.database().ref("/Usuario").orderByKey();
query.once("value")
.then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
// key will be "ada" the first time and "alan" the second time
key = childSnapshot.key;
starCountRef = firebase.database().ref("/Usuario/"+key);
starCountRef.on('value', function (snapshot) {
console.log(snapshot.val());
usuarios.push([key,snapshot.val()]);
});
});
}); }
And the result show me the values:
Related
I'm trying to replace the [0] for the index value obtained in the code above.
The data[0] is coming from a Json file, and the index value is coming from the month selection.
So my goal is to update the data coming from JSON file after the user select a month from the drop down menu.
//Getting the index after selecting a month:
months.forEach((el, index) => {
el.onclick = function () {
const indexValue = Number(index);
const monthSelected = (monthText.textContent = this.innerHTML);
console.log(monthSelected);
console.log(indexValue);
return indexValue;
};
});
//Here's is where I need to change that hard coded 0 for something:
// Step2
const jsonData = fetch("data.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
const generalData = data[0];
Trying to re-use the index inside the []
I did it guys!!! , well, the main goal of this project was to update the UI info inside the cards after selecting any given month. As you can see in the SS.
Now I have to find out how to solve another challenges on this project.
Screen Shot
I would just set it as global variable.
months.forEach((el, index) => {
el.onclick = function () {
var indexValue = Number(index);
const monthSelected = (monthText.textContent = this.innerHTML);
console.log(monthSelected);
console.log(indexValue);
};
});
Then would use it as index for data array.
// Step2
const jsonData = fetch("data.json")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
const generalData = data[indexValue];
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);
});
});
});
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am pulling data from Firebase. I want to extract values and save them in the array. After that I will use that array values as strings in my application. The problem is when I push values from DB to array, it adds undefined at the end of the array. And when I want to see the value of array (carUserDetails[0]) it returns undefined, but should return a string "BMW"
var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);
var carUserDetails = [];
refModels.once('value').then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var usersValue = childSnapshot.val(); //get the values of the object
carUserDetails.push(
usersValue.carMake,
usersValue.carYear,
usersValue.carModel,
usersValue.carTrim
);
});
});
console.log(carUserDetails);
console.log(carUserDetails[0]) // returns undefined too
So what could be the problem
So yes it an asynchronous call issue. See the fix
var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);
var carUserDetails = [];
refModels.once('value').then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var usersValue = childSnapshot.val(); //get the values of the object
carUserDetails.push(
usersValue.carMake,
usersValue.carYear,
usersValue.carModel,
usersValue.carTrim
);
});
$scope.getValueFromArray(); //call function here
});
$scope.getValueFromArray = function(){
console.log(carUserDetails[0]); returns "BMW"
}
I think it's because you are too early calling console.log remember reading firebase value is asynchronous. You should put your console, inside function (snapshot) and after snapshot.forEach
refModels.once('value').then(function (snapshot) {
snapshot.forEach(function (childSnapshot) {
....
});
console.log(carUserDetails);
});
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.
I'm able to query my users array with an e-mail address and return the user's account info:
users.orderByChild('email').equalTo(authData.user.email).once('value').then(function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.key); // 'users'
console.log(snapshot.child('email').key); 'email'
...
How do I get the key (-KiBBDaj4fBDRmSS3j0r). snapshot.key returns users. snapshot.child('email').key returns email. The key doesn't appear to be a child, i.e., it appears to be in between users and email.
You could do something like this:
var key = Object.keys(snapshot.val())[0];
Ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
Realtime database:
For this you can simple use: snapshot.key
snapshot = firebase.database.DataSnapshot
this.app.database()
.ref('/data/')
.on('value', function(snapshot) {
const id = snapshot.key;
//----------OR----------//
const data = snapshot.val() || null;
if (data) {
const id = Object.keys(data)[0];
}
});
Firestore:
snapshot.id
snapshot = firebase.firestore.DocumentSnapshot
this.app.firestore()
.collection('collection')
.doc('document')
.onSnapshot(function(snapshot) {
const id = snapshot.id;
//----------OR----------//
const data = snapshot.data() || null;
if (data) {
const id = Object.keys(data)[0];
}
});
users.orderByChild('email').equalTo(authData.user.email) is a Query (doc) that you have built by "chaining together one or more of the filter methods". What is a bit specific with your query is that it returns a dataSnapshot with only one child, since you query with equalTo(authData.user.email).
As explained here, in this exact case, you should loop over the returned dataSnapshot with forEach():
Attaching a value observer to a list of data will return the entire list of data as a single snapshot which you can then loop over to access individual children.
Even when there is only a single match for the query, the snapshot is
still a list; it just contains a single item. To access the item,
you need to loop over the result, as follows:
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
// ...
});
});
Similar to camden_kid, I used Object.keys(arr), but in three lines:
var arr = snapshot.val();
var arr2 = Object.keys(arr);
var key = arr2[0];
console.log(key) // -KiBBDaj4fBDRmSS3j0r
I found new way to get the data based on snapshot key -
firebase.database().ref('events').once('value',(data)=>{
//console.log(data.toJSON());
data.forEach(function(snapshot){
var newPost = snapshot.val();
console.log("description: " + newPost.description);
console.log("interest: " + newPost.interest);
console.log("players: " + newPost.players);
console.log("uid: " + newPost.uid);
console.log("when: " + newPost.when);
console.log("where: " + newPost.where);
})
})