Firebase Database workouts issues - javascript

I created the Database in firebase and used for my hybrid application, Let you explain the application scenarios below.
I have a hybrid application in this app, We need to insert, update, delete, kind of operations using firebase.
As of now, I did the insert method kind of queries alone using code. So the thing is I want to create multiple tables in firebase is it possible ?
Because For example, I've userTable, adminTable and guestTable, So If I need to insert one userData before that I need to check already the user found or not in Admin table this kind of scenarios How can I do in firebase ?
How can I maintain multiple tables in the firebase Database dashboard?
I have the table name called "Inmate_Data" now I want to add one more Table called "Admin_Data" and How can I do a joint operation like connecting two table using Firebase.
And, I tried to add one more table using Import JSON option But while I inserting new JSON the old Table got deleted like the "Inmate_Data" deleted and new JSON got added.
Please guide me in this.
#FrankvanPuffelen - Please find the below coding part.
Actually, I created the form and saving the data into firebase using below code.
$scope.addInmateDataToFirebase = function() {
alert('Firebase')
var newPostKey = null;
// Get a key for a new Post.
newPostKey = firebase.database().ref().child('Tables/Inmate_Data').push().key;
alert(newPostKey);
var dateofjoin= $filter('date')($scope.IMDOJ, 'yyyy-MM-dd');
var dateofbirth= $filter('date')($scope.IMDOB, 'yyyy-MM-dd');
console.log("Result"+ newPostKey);
var admissionId="KAS"+pad(newPostKey,5);
console.log("Padded number"+ pad(newPostKey,5));
alert(admissionId);
// A post entry.
var postInmateData = {
Inmate_ID: admissionId,
Inmate_Name: $scope.IMfirstnameText,
Inmate_Perm_Address1: $scope.IMAddress1 ,
Inmate_Perm_Address2: $scope.IMAddress2 ,
Inmate_Perm_City: $scope.IMCity,
Inmate_Perm_State: $scope.IMState,
Inmate_Perm_Pincode: $scope.IMPincode,
Inmate_ProfilePhotoPath: $scope.IMProfilePhotoPath,
Inmate_Temp_Address1: $scope.IMLocAddress1,
Inmate_Temp_Address2: $scope.IMLocalAddress2,
Inmate_Temp_City:$scope.IMGcity,
Inmate_Temp_State: $scope.IMGstate,
Inmate_Temp_Pincode: $scope.IMGpincode,
Inmate_Mobile: $scope.IMMobile,
Inmate_DOB: dateofbirth,
Inmate_EmpOrStudent: $scope.IMEmpStudent,
Inmate_DOJ: dateofjoin,
Inmate_ID_Type: $scope.IMIdcardType,
Inmate_ID_No: $scope.IMIdcardno,
Inmate_ProffPhotoPath: $scope.IMProofPhotoPath,
Inmate_Status:$scope.IMStatus
};
// Write the new post's data simultaneously in the list.
var updates = {};
updates['/Tables/Inmate_Data/' + newPostKey] = postInmateData;
return firebase.database().ref().update(updates).then(function() {
//$scope.ClearInMateDetails();
alert(admissionId);
$scope.statusMessage = "Welcome to Kasthuri Hostel. Your Admission ID is" + admissionId +" . Enjoy your Stay.";
//sendSMS('9488627377',$scope.statusMessage);
alert('Inmate data stored in cloud!');
$scope.ClearInMateDetails();
}, function(error) {
alert (error);
});
}
Now the Inmate_data got stored. and I need to save the Inmate_alloc_data into firebase but before that, I need to check whether the Inmate_Id available in the Inmate_Data table in firebase.
Please find the below snap :
My suggestions :
For example like above screenshot now I've multiple tables like "Inmate_Data", "Inmate_Alloc", and more Shall I get all the data and store it in a local SQLite Db like same as "Inmate_Alloc_tbl" and "Inmate_Data_tbl" and finally If I update any values finally I want to get all values in the local database and store it in the firebase. Is it possible to handle ?
If so I can manage lots of SQL queries, right ? Because via firebase we can't able to manage all queries right ?
Please suggest your ideas.

Related

How to retrieve a specific data from Firebase

I am designing a website where when the user comes and enters his email id, a corresponding value gets printed on the website.
I have the below data on my real-time firebase database.
How do I write a javascript function in my JS file so that when a user enters his/her email-id, the value of the total gets printed on the website?
I have tried something like this:
function getdata(){
var email=document.getElementById("email").value;
firebase.database().ref('0/'+email).once('value').then(function(snapshort){
var total=snapshort.val().total;
document.getElementById("total").innerHTML=total;
})}
I think you're trying to perform a query based on the email property of the node.
In that case, it'd be:
firebase.database().ref()
.orderByChild("email")
.equalTo(email)
.once('value').then((results) => {
results.forEach((snapshot) => {
let total = snapshot.val().total;
document.getElementById("total").innerHTML=total;
});
});
I recommend reading the Firebase Realtime Database documentation end-to-end, as it should answer many of the questions you may have about the API. A few hours spent there now, will save you many hours down the line.

Generate a custom unique id and check it does not exist before creating a new user with MySQL and sequelize

I'm trying to create a unique id that is 8 characters long for each new user added to a MySQL database. I am using Sequelize along with express to create users. I've created my own custom function: idGen() that simply returns a randomized 8 character string. Using express router I can handle/validate all the form data used to create a new user. The issue I am having is when I generate a new ID I want to check to make sure that ID does not already exist in the database. So far I have this solution:
Users.findAll().then( data => {
tableData = data.map(id => id.get('id'));
while( tableData.includes(uid) ){
try {
uid = idGen(8);
} catch( error ){
return res.status(400).json( error )
}
}
}).then( () => {
Users.create({
id: uid,
name: req.body.name,
email: req.body.email
})
}).then( user => res.json(user) );
This block of code is actually working and saving the new user in the DB, but I am almost certain that this is not the best / right way of doing this. Is anyone able to point me in the right direction and show me a better/proper way to check the random generated ID, and recall idGen(if needed) in a loop before adding a new user?
Many Thanks!
instead of find all and then filter in Javascript, why don't you select from the database right away?
an alternative way I could think of is using a filter like bloom or cuckoo.the false positive rate should be low.
load ids to redis, probably with redis bloom (https://github.com/RedisBloom/RedisBloom)
check the new generated id with bloom filter.
if exists => re-generate id. if not, insert. there could be false positive but the rate is low and you can handle it just the same.
pros:
- no need to check again database every time.
- checking with bloom filter is probably much faster than db.
- scaling redis is easier than db.
cons:
- need redis and redis bloom.

How to store user input into SQLite3 table using javascript?

I have a basic web page with two text boxes, one for the user's first name and the other for the user's last name. Once their name is entered, I want to save the data into a sqlite3 table via a button. The script I currently have in place is as follows:
<script>
document.getElementById('btnSave').addEventListener('click', AddRecord);
function AddRecord()
{
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('C:/Users/RedCode/Documents/Programming Tutorials/Practice Site/test.db');
var FirstName = document.getElementById('txtUsername').value;
var LastName = document.getElementById('txtSurname').value;
db.run('INSERT INTO testtbl(First_Name, Last_Name) VALUES("FirstName", "LastName")');
db.close();
}
</script>
When I check the table, the data is not stored in it. What is the correct way to save that user's data into the table?
This is not something you can achieve in browser. The tool you are trying to use is designed to be used with node which has access to the file system and can make calls to read and write from the sqlite.db file at will. Browsers cannot access the file system in this way.
If you really really need sqlite for real SQL type queries in your web app you can use something like: https://github.com/kripken/sql.js/ which is designed to be used in browser.
For regular storing of data in browser however there are inbuilt datastore tools
Web Storage
Index DB

In firebase (javascript), how can I get data for the currently logged in user?

I've spent a few days researching for the solution. I have found many answers that were quite helpful, but still I haven't been able to find a solution that fully resolved my problem. Basically all I want to do is to get current user's data (stored in firebase realtime database) and display them on the user's screen.
So far, I can display data for all the user. But how can I have it display data for only the current user? (How can I get the push key of only the current user?)
I'm not an experienced programmer (less than a year). Please use a language that is easy to understand.
I've gone through all the firebase documentation. Please don't just give me the copy of the documentation or the link to it.
Screenshot: Firebase realtime database
Screenshot: JavaScript function for retrieving current user's data
Additional JavaScript screenshot
User data is wherever you choose to store it--other than name, email, and a few other fields, the User object cannot actually store any other info. Therefore, you will need to decide where in the database you want to keep your extra data.
Assuming you choose to create a collection users with children named by uid, and you store the users' countries in those documents, the following will get you a specific user's data and you can use whatever fields you'd like from there:
let ref = database.ref('/users/' + currentUser.uid).once('value').then(function(snapshot) {
let userData = snapshot.val();
console.log(userData.country);
}
Here you go!
function showUser(){
var usref=firebase.database().ref("countries/"+uid);
//uid here is the unique code u gave to the specif user
usref.once('value', function(snapshot) {snapshot.forEach(function(childSnapshot) {
if((childSnapshot.key)=="country"){
var country = childSnapshot.val();
//use this variable here enter code here
window.alert(country);//just for checking!!!
}
if((childSnapshot.key)=="age"){
var name = childSnapshot.val();
//use this variable here
window.alert(name);//just for checking!!!
}
});
});
}
I hope this code works for you.

Need helping retrieving data from Firebase

So I've been using Firebase as a database for my website (this is a web based project, using HTML, CSS and JS) and I'm running into a problem retrieving data from it.
Basically this site allows users to create a profile for a character (they can fill in the name, the characters stats etc...) and when they click submit, it'll save the values they filled out to the database.
The values are saved perfectly fine, but when I go to retrieve the data the command doesn't seem to do anything.
So in order to get the profiles, I've been trying to use this bit of code to get whatever is stored at the specified .ref(path):
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
Which according to the Firebase docs should return a list of keys at the path that I specified in .ref(). However whenever I try to access whatever is in the var, it just gives me the string that contains a link to the database that looks like this:
https://#mydatabaseurlhere.firebaseio.com/users/uid/chars
Where #mydatabaseurlhere is the url I created on the Firebase app, and the uid is the authenticated user's ID.
I've been reading the docs, and its telling me that the above code should return a list of whatever is at the path that I specified, but so far it just gives me a link. Is there something I've been missing from the Docs that'll allow me to access whatever data is currently in the database? Because I've tried to take a snapshot using .once() to no avail either. I've also set the rules on /users/ to allow anyone to read/write to the database but I'm still not able to access the data (or maybe I am accessing, I'm just missing how to retrieve it).
Either way, I'm wondering how one can go about accessing this data, as I'm extremely confused as to why I can't seem to retrieve the data that has been successfully written to the database.
You're defining a query. But that doesn't yet retrieve the data.
To retrieve the data, you need to attach a listener. For example:
var uid = firebase.auth().currentUser.uid;
var getChar = firebase.database().ref('/users/' + uid + '/chars/').orderByKey();
getChar.on('value', function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val());
});
});

Categories