Select child_added, firebase - javascript

I am creating a query in Firebase, and I have as data the uid, how can I improve the query to get (name, surname) if I have a structure like the following.
I just want the data of the logged in user.
My code is this:
const v_uName = document.getElementById('id_nameU');
var v_userId = firebase.auth().currentUser.uid;
console.log(v_userId);
var v_ref1 = firebase.database().ref().child('/ad_persona/');
v_ref1.on('child_added', function(v_snap1){
v_ref1.child(v_snap1.key).on('child_added', function(v_snap2){
v_ref1.child(v_snap1.key).child(v_userId).on('value', function(v_snap3){
console.log(v_snap3.val());
});
});
});

Related

Displaying firebase realtime database entries using Javascript

I am using the firebase realtime database to display information that users on my web app can submit. A submit page is in use where particular users submit info to my database, where (this is where i'm stuck) that info is displayed on the said persons profile page.
This is what the database looks like
This is what the submit form looks like
This is the submit JS
function writeUserData() {
var user = firebase.auth().currentUser;
var userDisplayName = user.displayName;
var userid = user.uid;
var getFieldID = document.getElementById('id_field').value;
var getFieldName = document.getElementById('name_field').value;
var getFieldDate = document.getElementById('dateField').value;
var getFieldTime = document.getElementById('timeField').value;
var getFieldDesc = document.getElementById('desc').value;
const db = firebase.database();
db.ref('teachers/' + getFieldID).push({
student_UID: userid,
student_displayName: userDisplayName,
teacher_ID: getFieldID,
teacher_name: getFieldName,
date: getFieldDate,
time: getFieldTime,
description: getFieldDesc
});
};
How do I then get that user data and display it on a particular page? I've had a look through most of the documentation on firebase for web and can't find anything.
Now with the DB, multiple submissions under the same 'id' can be submitted and created with the .push function. My issue is retrieving the data and being able to display all submissions under a particular child (eg test1, test 2) on the webpage.
Thanks for any help!
You'll want to save a copy of the reference.
const teacherRef = db.ref('teachers/' + getFieldID).push({
student_UID: userid,
student_displayName: userDisplayName,
teacher_ID: getFieldID,
teacher_name: getFieldName,
date: getFieldDate,
time: getFieldTime,
description: getFieldDesc
});
console.log('teacherRef key', teacherRef.key);
teacherRef.once('value', snapshot => {
const value = snapshot.val();
console.log('saved value', value);
})

How to iterate a firebase database using javascript?

I need to iterate the users of my Firebase Database. I have a token for each user, and I want to send a notification to each user of the database.
My database looks like this:
console.log('Sending a notification to all users');
var ref = functions.database.ref('/users');
for (var token in ref){
console.log('Hello from: '+ ref.token);
}
Your ref is just a reference to a specific path in Firebase Realtime Database. You haven't queried it, so you don't have anything back yet. Try this:
console.log('Sending a notification to all users');
var ref = functions.database.ref('/users');
// Query the database
ref.once('value').then((usersSnapshot) => {
// Get back all the user records and iterate through them.
usersSnapshot.forEach((userRecordSnapshot) => {
// I'm guessing your record id is the token?
const token = userRecordSnapshot.key
// To get the other values, for example
const email = userRecordSnapshot.val().email
});
});```

How do I update an object in Firebase specific property?

I am trying to update a User in Firebase using Angular 4 with AngularFire2. In the user object that tis saved to the firebase database, I want to insert another object into an array property. In my service I am trying to do this functionality (I already have everything in keys etc also)
generateUserCharacterList(){
this.genCharList = new CharacterList(x, y, z)
this.UserListOfCharacters.push(this.genCharList)
//Other code...
}
This does not work though
The Update specific fields documentation indicated usage of the .update method.
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
I am considering that you are using the firebase realtime database as compared to the firestore.
You should take the value of the array in a variable, change the value, and then call the update method on the object ref with that new value. Here is the code sample for the explanation:
let userRef = db.object('users/aad1asd123-123asd');
let user = userRef.valueChanges();
let listOfChars = user.listOfChars;
listOfChars.push('a');
listOfChars.push('b');
listOfChars.push('c');
listOfChars.push('d');
userRef.update({listOfChars: listOfChars});

Searching Through Firebase for Data

I am trying to get data out of my firebase for a specific user via the realtime database. Whenever a user signs up and new piece is added to the stripe_customers piece of the database. How can I get the customer_id for each customer?
Current Customer -
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
Current Database Layout - Database Layout
Thanks!
I am not sure whether I understand you clear, but it seems it is quite easy something like:
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var dbRef = firebase.database().ref('stripe_customer/' + userId + '/customer_id');
dbRef.once('value', snapshot=> {
if (snapshot.exists()){
var custumerId = snapshot.val().customer_id;
_goAheadWithCustomerId(custumerId);
}
})
_goAheadWithCustomerId(c){
console.log('Customer Id is :', c);
}

Checking data in deep array with includes (Firebase retrieve data JS)

So I am new to the Firebase database and what I like about it is that I don't have to build a whole backend for just storing some simple data. What I am trying to do is pushing data to an array that I like to recieve from firebase. Then after that I would like to check if the email that was filled in, is included in the data from the firebase database. But because it's firebase and it has multiple arrays, objects etc I don't know how to check that. So the flow is: User fills in data, Applications makes a call to the firebase db and the Application is retrieving the current data from firebase. Then the Application will check if the data that is inputed is already there, and if so, will throw an alert that the data is already in the database. If not, the data will be submitted.
Also, I am wondering if this is the right way to retrieve data from the database:
Main.js
function writeUserData() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
firebase.database().ref('/aanmeldingen/').push({
username: name,
email: email,
});
var dbRef = firebase.database().ref().child('/aanmeldingen/');
dbRef.on('value', snapshot => {
const snap = snapshot.val();
const array = [];
array.push(snap);
console.log(array);
const res = array.includes(email);
console.log(res);
console.log(email);
});
}
Output in console
As you can see this returns multiple data. The include function will check on the submitted emailadress. This returns false even I had inputted "info#webpack.com". How can I check the right data object? It has to check all objects under "0" and return in the console if the submitted emailadress is already there.
I haven't tested it yet but i hope you get the idea. Also this is not the most efficient way to do this.
function ifEmailExist(arr,email){
var _t = 0;
for(var x in arr){
for(var y in arr[x]){
if(arr[x][y].email){
if(arr[x][y] === email){
_t++;
}
}
}
}
return _t;
}
Usage:
if(ifEmailExist(arr,"info#webpack.com") > 0){
//do stuff
}
You should use child_added instead of value. Whenever a new node is added in database, child_added will trigger and then you can take action on the data.
var dbRef = firebase.database().ref().child('aanmeldingen');
dbRef.on('child_added', snapshot => {
var username = snapshot.val().username;
var email = snapshot.val().email;
console.log(username);
console.log(email);
});

Categories