Query data on firebase for web - javascript

So I'm building a music platform, using firebase, where users can upload their songs. When a user logs in, I save their data on the "usuarios" node. And when they upload a song, I push to the "musicas" node (child of usuarios).
This way, I know who uploaded the song.
But the problem is: I want to get a list of all the last 15 songs uploaded. How do I do that? Did I structure my data wrong?
Here's what I tried:
var musicsRef = firebase.database().ref('usuarios').orderByChild('musicas');
musicsRef.on('value', function(snapshot) {
console.log(snapshot.child('musicas');
});
Here's my database structured:

With Firebase (like with most NoSQL databases) you often end up modeling your data for the way you app wants to consume it. So if you need to find a global list of the most recently uploaded songs, you should keep such a list:
songsByDate
$pushIdOfSong: true
You'll note that we don't keep a real value in this list. It is just the ID of each song and a true value. This is called a secondary index and so command that we explain it in our documentation on creating a scalable data structure.
With that structure in place you can query with:
var recents = ref.child('songsByDate').orderByKey().limitToLast(15);
recents.on('child_added', function(snapshot) {
var key = snapshot.key;
// load the song by its key
});
I highly recommend reading this article on NoSQL data modeling.

Related

How to get data from back end side, to use it in the browser side?

I am new to programming, and I heard that some guys on this website are quite angry, but please don't be. I am creating one web app, that has a web page and also makes som ecalculations and works with database (NeDB). I have an index.js
const selects = document.getElementsByClassName("sel");
const arr = ["Yura", "Nairi", "Mher", "Hayko"];
for (let el in selects) {
for (let key in arr) {
selects[el].innerHTML += `<option>${arr[key]}</option>`;
}
}
I have a function which fills the select elements with data from an array.
In other file named: getData.js:
var Datastore = require("nedb");
var users = new Datastore({ filename: "players" });
users.loadDatabase();
const names = [];
users.find({}, function (err, doc) {
for (let key in doc) {
names.push(doc[key].name);
}
});
I have some code that gets data from db and puts it in array. And I need that data to use in the index.js mentioned above, but the problem is that I don't know how to tranfer the data from getData.js to index.js. I have tried module.exports but it is not working, the browser console says that it can't recognize require keyword, I also can't get data directly in index.js because the browse can't recognize the code related to database.
You need to provide a server, which is connected to the Database.
Browser -> Server -> DB
Browser -> Server: Server provides endpoints where the Browser(Client) can fetch data from. https://expressjs.com/en/starter/hello-world.html
Server -> DB: gets the Data out of the Database and can do whatever it want with it. In your case the Data should get provided to the Client.
TODOs
Step 1: set up a server. For example with express.js (google it)
Step 2: learn how to fetch Data from the Browser(Client) AJAX GET are the keywords to google.
Step 3: setup a Database connection from you Server and get your data
Step 4: Do whatever you want with your data.
At first I thought it is a simple method, but them I researched a little bit and realized that I didn't have enough information about how it really works. Now I solved the problem, using promises and templete engine ejs. Thank you all for your time. I appreciate your help)

How to Store and Access Large Files in NodeJS Web Application

If I want to allow a user to upload a video in a post, then what's the best way to store it so that I can access it later? I am currently just using a INSERT query to upload it to a PostGres SQL database field, but it's extremely slow.
Is there another method or best practice to store large files like this and access it quickly and efficiently?
var video = videoFile ? "'\\x" + videoFile.buffer.toString('hex') + "'" : "NULL";
let insertQuery = "INSERT INTO posts (video) VALUES(" + video + ") RETURNING *";
Above is the code I'm using right now to insert the file into the database.
Do not store the whole video into the database. These 2 steps below might be a better solution:
1) Upload the video file to the cloud storage. See Google Cloud Strage and Amazon S3. There are many other options as well. Go do some comparison yourself.
2) You will have a link or ID (or key in S3) to access a file. Store all those links or ID into your database. Please take a look at this GCS doc and this S3 question.
Also, make use of the non-blocking I/O which is a good thing of node.js. In your case, you may try something like this:
let insertQuery;
let promisesList=[];
for(let vid of videoIds){
insertQuery = "INSERT INTO posts (videoId) VALUES($1) RETURNING *";
promisesList.push(client.query(query,[vid]));
}
await Promise.all();

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.

Firebase Database workouts issues

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.

How to load a file into a byte array in JavaScript

I'm am developing a mobile application with cordova. The applications needs in some point to be off-line which means that it has to have data in an internal database.
The data consists on a bunch of fields some of them are links to files. For example:
var restaurant = {
name: 'Restaurant X'
address: 'So far'
logo: http://www.restaurantX.com/logo.png
image: pics/restaurant-x.jpg
}
When the user decides to be off-line we should extract all the relevant information from the database (This point is cleared) and download all the related images (This is where I am stuck). At this point I thought in two options the first one is download all the files to the mobile as files or as data in the database, however, the project chief said that It was mandatory that images were saved as blob on the database.
I've been looking for a function to convert the content of the file into a byte Array for saving it into the database but I need a syncronous function since I have to wait for the pictures before of saving the row in the database.
function(tx, row){
var query = "INSERT INTO Restaurants (name, address, logo, image) values (?,?,?,?)";
var logo = null; // I need to fill it with the logo
var picture = null; // I need to fill it with the picture
tx.executeSql(query, [row["nombre"], row["address"],logo,picture], onSuccess, onError);
});
I'm sorry if the question is too basis, I'm practically new at JavaScript.
You should definitely take a look at promises, if your image serialization routine is async and you want to store it on serialize success. More detailed info about promises you can check here

Categories