Retrieving Data From Firebase Not Displaying Correctly in Console - javascript

I'm able to display the correct data from my Firebase child in the console with the following code:
var ref = firebase.database().ref('requests');
ref.on('value', gotData, errData);
function gotData(data) {
var scores = data.val();
console.log(scores);
}
Which displays the following in the console:
So when I try to use this snippet of code to retrieve the email:
function gotData(data) {
var scores = data.val();
console.log(scores);
var keys = Object.keys(Email);
console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var emails = email[k].email;
console.log(emails);
}
}
it's displaying the following error:
but I'm not fully understanding why I'm getting this error when this is very similar to other peoples solution.
Anyone know why I'm getting this error when there is an actual value for the email key?

To get the email simply to do this:
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email=child.val().Email;
});
});
Assuming you have this database:
requests
randomid
Email: email_here
You need to be iterating inside the randomid to be able to access the property Email

Related

Get Key Value Given Other Key Value in FireBase

I am trying to find a way to find the value of the id given the email.
For example, If I had email2#gmail.com, It would give me the ID 108454568498950432898.
All emails are unique and there will be no repetition of emails.
This is my user tree:
Note: In the image it says email2 instead of email2#gmail.com. Ignore this
Here's my code so far:
(Code won't run obviously but it's easier to enter code using the embed)
var users;
var givenEmail = "email2#gmail.com";
var neededID;
var dataRef = firebase.database().ref('users');
dataRef.on('value', (snapshot) => {
const data = snapshot.val();
users = data;
});
var usersArray = Object.keys(users);
for(i = 0; i < usersArray.length; i++) {
if(users[i].email == givenEmail) {
neededID = i;
break;
}
}
I recommend using a query to perform the filtering on the server, instead of downloading the entire users node and filtering in your application code as you now do.
var givenEmail = "email2#gmail.com";
var dataRef = firebase.database().ref('users');
var query = dataRef.orderByChild('email').equalTo(givenEmail);
dataRef.once('value', (snapshot) => {
snapshot.forEach((userSnapshot) => {
console.log(userSnapshot.val().id);
});
});
Well, I think you are almost there.
users[i].email
you can retrieve the email using this method, and similarly you can do it with id too
users[i].id
Please note that you wanted to find email2#gmail.com but your firebase only have email2
Maybe you would want to change that

Google spreadsheet error TypeError: Cannot read property 'filter' of undefined

I am taking data from a sheet and then converting it to json, so far all good. But when I am trying to take out specific data from arrays but it is making undefined if I get data from array, but when I use raw json data everything works fine
function doGet(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users');
var userData = getUser(ss);
var array = userData.user.filter(function b(e) { return e.id == 11281 });
console.log(array)
}
function getUser(ss){
var usr = {};
var usrArray = [];
var data = ss.getRange(2,1,ss.getLastRow(), ss.getLastColumn()).getValues();
for (var i=0, l=data.length; i<l; i++){
var dataRow = data[i];
var record = {};
record['id'] = dataRow[1];
record['name'] = dataRow[0];
record['profession'] = dataRow[2];
usrArray.push(record);
}
usr.user = usrArray;
var result = JSON.stringify(usr);
return result;
}
ERROR: TypeError: Cannot read property 'filter' of undefined
Error picture
Sheet data picture
If I console log the result directly the it is working fine like this: Output
JSON.stringify returns a string — the getUser function returns a string. And you're trying to read the user property from it which returns undefined.
You could do a JSON.parse in doGet but it's simpler to just return the usr object from getUser.
function getUser(ss) {
const usr = {}
const usrArray = []
// populate usrArray
usr.user = usrArray
return usr
}
And there's another issue. You're setting record['id'] to dataRow[1] but it should be dataRow[0] since id is the first column (This is why the shared screenshot has the name in the id property). You could also refactor the code.
function getUser(ss) {
const data = ss
.getRange(2, 1, ss.getLastRow(), ss.getLastColumn())
.getValues()
const users = data.map((row) => ({
id: row[0],
name: row[1],
profession: row[2],
}))
return {
user: users,
}
}
I would also recommend renaming the user property to users for clarity.

I am making a firebase-database list and don't know how to make it remove items from the database

I am pretty new to Javascript, a couple of months in. Essentially, I am trying to make a simple online-based shared shopping-list for a class. I can add to the database, I can show the items as a list, right now my issue is how to remove. I have given the buttons the keys of the database entry they are attached to, as ID, hoping that that would work, but I can't find a way to use the ID. As you can see, i've been testing it by seeing if I can console.log the key, but no luck so far. I've seen a dozen videos and tried dozens of guides, and I hope you can help me; How to I make it so when I click the button, the corresponding entry in the database is deleted? Sorry that the code is a bit of a mess, right now, it is mostly strung together from old code and guides.
var database = firebase.database();
var ref = database.ref('Varer');
ref.on('value', gotData, errData);
function gotData(data){
document.getElementById('Liste').innerHTML = "";
var kbdt = data.val();
var keys = Object.keys(kbdt);
for (var i = 0; i < keys.length; i++){
var k = keys[i];
var kob = kbdt[k].varer;
var btn = document.createElement('button');
var btnText = document.createTextNode('Done')
var opg = document.createElement('li');
var opgnvn = document.createTextNode(kob);
opg.appendChild(opgnvn);
btn.appendChild(btnText);
opg.appendChild(btn);
opg.setAttribute('id', k);
opg.setAttribute('class', 'button');
document.getElementById('Liste').append(opg);
btn.addEventListener('click', function(){
deleteTask(this.id)});
}
}
function errData(err){
console.log('error!');
console.log(err);
}
function deleteTask(id) {
console.log(id);
}
function Indkob() {
var nyVare = document.getElementById('tilfoj').value;
document.getElementById('Liste').innerHTML = "";
var data = {
varer: nyVare
}
var result = ref.push(data);
console.log(result.keys);
}

Iterate through Firebase ref to load its children

I want to individually load each child of an object from firebase.
A nonworking snippet of code to better explain the idea is given below:
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('/users/'+userId+"/foo/list").once('value').then(function(list) {
var reffoo = firebase.database().ref().child("/foo/");
for (var i = 0; i < list.length; i++) {
ref = reffoo.child(list[i]);
$scope.foo[ref] = $firebaseObject(ref);
}
});
As per my analysis the issue is, $firebaseObject makes async call to firebase but don't know how to make it work?
One option is to obtain a ref to your collection and iterate over using
data snapshot api i.e.,
var ref = firebase.database().ref('/users/'+userId+"/foo/list");
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
$scope.foo[childKey] = childData;
});
});
If you want to maintain actual angularFire reference to an object then $firebaseArray comes to help:
var list = $firebaseArray(ref);
// add an item
list.$add({ foo: "bar" }).then(...);
// remove an item
list.$remove(2).then(...);
// make the list available in the DOM
$scope.list = list;

Javascript variable is an array of objects but can't access the elements

I am using Firebase database and Javascript, and I have code that will get each question in each category. I have an object called category will contain the name, the questions, and the question count, then it will be pushed into the list of categories (questionsPerCategory). Inside the the callback function I just do console.log(questionsPerCategory). It prints the object (array) that contains the categories and questions. Now my problem is that when I do console.log(questionsPerCategory[0]) is says it's undefined, I also tried console.log(questionsPerCategory.pop()) since it's an array but it's also undefined. Why is that? Below is the code and the image of the console log. Additional note: CODE A and C are asynchronous, CODE B and D are synchronous.
this.getQuestionsForEachCategory = function(callback, questions, questionsPerCategory) {
var ref = firebase.database().ref('category');
var questionRef = firebase.database().ref('question');
console.log('get questions for each category');
// CODE A
ref.once("value", function(snapshot) {
// CODE B
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var category = {
category_name: childData.category_name
};
// CODE C
questionRef.orderByChild("category_name").equalTo(childData.category_name).once("value", function(questionSnapshot){
var count = 0;
var q = [];
// CODE D
questionSnapshot.forEach(function(childQuestionSnapshot) {
var questionObj = childQuestionSnapshot.val();
count++;
questions.push(questionObj.question);
q.push(questionObj.question);
});
category.questions = q;
category.questionCount = count;
questionsPerCategory.push(category);
});
});
callback(questionsPerCategory);
});
};
The callback(questionsPerCategory); should happen when all async calls are finished.
Right now the questionsPerCategory is not ready when the callback is called.
I would use Promise API to accomplish this.
Depending on the Promise library you are using, this can be accomplished in a different ways, e.g. by using bluebird it looks like you need map functionality.
Try this code:
this.getQuestionsForEachCategory = function(callback, questions) {
var ref = firebase.database().ref('category');
var questionRef = firebase.database().ref('question');
console.log('get questions for each category');
var questionsPerCategory = [];
// CODE A
ref.once("value", function(snapshot) {
// CODE B
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var category = {
category_name: childData.category_name
};
// CODE C
questionRef.orderByChild("category_name").equalTo(childData.category_name).once("value", function(questionSnapshot){
var count = 0;
var q = [];
// CODE D
questionSnapshot.forEach(function(childQuestionSnapshot) {
var questionObj = childQuestionSnapshot.val();
count++;
questions.push(questionObj.question);
q.push(questionObj.question);
});
category.questions = q;
category.questionCount = count;
questionsPerCategory.push(category);
});
callback(questionsPerCategory);
});
});
};

Categories

Resources