Searching Through Firebase for Data - javascript

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);
}

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 do CRUD operations in Firebase with CurrentUserId?

I'm creating a simple website and i'cant use firebase realtime databases crud operations with currentUserId.
My auth system working good; i can signIn/signUp/signOut on database. And i can write data to firebase with getting inputs from form.
//GETTING DATA WITH FORM
// Listen for form submit
document.getElementById('form').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
// Get values
var name = getInputVal('name');
var sets = getInputVal('sets');
var reps = getInputVal('reps');
var weights = getInputVal('weights');
// Write data
writeData(name, sets, reps, weights);
// Clear form
document.getElementById('form').reset();
}
// Function to get form values
function getInputVal(id){
return document.getElementById(id).value;
}
//CRUD OPERATIONS
// Reference
var DataRef = firebase.database().ref('users/' + 'exercises/');
// Write data to database
function writeData(name, sets, reps, weights){
var newDataRef = DataRef.push();
newDataRef.set({
name: name,
sets: sets,
reps: reps,
weights: weights,
});
}
I didn't want to start reading, updating and deleting until I solved this id problem.
So how to do CRUD operations with each users with id? What can i do?
Are you asking how to write data in a location that is specific to the current user? If so:
var currentUser = firebase.auth().currentUser;
var DataRef = firebase.database().ref('users/' + currentUser.uid + '/exercises/');
Note that this only works if the current user is guaranteed to be already signed in. If you can't guarantee that, put the above code in an auth state listener.

firebase functions + realtime database - database structure and code

I'm on a simple application:
It's my first try with firebase functions + realtime database.
The functions are going to be called by an external client application (e.g.: android).
if it was not javascript + nosqldb I would not have a problem, but here I am stuck, because I'm not sure for the best db structure and about transaction-like operations.
I. stored data:
user profile (id, fullname, email, phone, photo)
tickets amount per user
history for tickets buyings
history for tickets usings
II. actions:
user buy some tickets - should add tickets to the user's amount AND add a record to buyings history
user use some tickets - should remove tickets from the user's amount AND add a record to usings history
So my base problem is this ANDs - if it was a SQL db i would use a transaction but here I'm not sure what is db structure and js code in order to achieve same result.
EDITED:
======== index.js =======
exports.addTickets = functions.https.onCall((data, context) => {
// data comes from client app
const buyingRecord = data;
console.log(‘buyingRecord: ‘ + JSON.stringify(buyingRecord));
return tickets.updateTicketsAmmount(buyingRecord)
.then((result)=>{
tickets.addTicketsBuyingRecord(buyingRecord);
result.userid = buyingRecord.userid;
result.ticketsCount = buyingRecord.ticketsCount;
return result;
});
});
====== tickets.js =======
exports.updateTicketsAmmount = function(buyingRecord) {
var userRef = db.ref(‘users/’ + buyingRecord.userid);
var amountRef = db.ref(‘users/’ + buyingRecord.userid + ‘/ticketsAmount’);
return amountRef.transaction((current)=>{
return (current || 0) + buyingRecord.ticketsCount;
})
.then(()=>{
console.log(“amount updated for userid [“ + buyingRecord.userid + “]”);
return userRef.once(‘value’);
})
.then((snapshot)=>{
var data = snapshot.val();
console.log(“data for userid [“ + snapshot.key + “]:” + JSON.stringify(data));
return data;
});
}
exports.addTicketsBuyingRecord = function(buyingRecord) {
var historyRef = db.ref(‘ticketsBuyingHistory’);
var newRecordRef = historyRef.push();
return newRecordRef.set(buyingRecord)
.then(()=>{
console.log(‘history record added.’);
return newRecordRef.once(‘value’);
})
.then((snapshot)=>{
var data = snapshot.val();
console.log(‘data:’ + JSON.stringify(data));
return data;
});
}
You would have to use the callback, the request on Android to add or read data have an onSuccess or OnFailure CallBack, i used this to trigger my new request.
You can check this on the doc here :)
Also if instead of using RealTime Database you use Firestore you can use the FireStore Transactions here is the info.

Select child_added, firebase

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());
});
});
});

Writing data to completely separate locations simultaneously using update()

In my firebase app when a new user signs up I add their initial data like displayname, emai , photourl to the database under the top level users node. This works fine.
Now when a user post a status, I want to upload the the post to top level statuses node where all user statuses are kept. And simultaneously I want to upload the post to current user's posts node i.e users/currentuser/posts.
I am following the methods shown on official firebase site here.
The problem is when I hit the post button nothing happens and no data is posted to the database
My function that gets invoked when the post button is clicked:
function postStatus(){
var ref = firebase.database().ref("allstatuses");
var user = firebase.auth().currentUser;
var newStatusRef = ref.push();
var newStatusKey = newStatusRef.key();
var statusData = {
status: postInput.val(),
likes: 0,
dislikes: 0
};
var updateUserStatus = {};
updateUserStatus["users/" + user.uid + "/" + newStatusKey] = statusData;
updateUserStatus["allstatuses/" + newStatusKey] = statusData;
if(user){
firebase.database().ref().update(updateUserStatus);
}else{
alert("please login");
}
}
What am I doing wrong?
According to the API reference link it is key not key()
Change this
var newStatusKey = newStatusRef.key();
to
var newStatusKey = newStatusRef.key;

Categories