Firebase set new unique ID - javascript

I'm new to firebase and practicing creating a ToDo application. So far this is my code:
Code:
var getUserRef = firebase.database().ref('users');
getUserRef.on('child_added', function(data) {
var name = data.child("name").val();
var email = data.child("email").val();
$('#loadData').append(`<tr><td>${name}</td><td>${email}</td><td>Edit Remove</td></tr>`);
});
function addUser() {
var database = firebase.database();
var name = $('#name').val();
var email = $('#email').val();
var newID = 4; // How can this be incremented?
database.ref('users/' + newID).set({
name: name,
email: email
});
}
Data Structure:
As you can see, everytime I create a new user, I am manually changing the newID variable.
My problem is I don't want to change it everytime I insert a new user. I want it to aumotically increment or generate a random unique ID.
Is there a way to do this in google firebase?

What you have here is a list of items. If you have such a list, it is common to use Firebase's push() method to add new items to it. This will generate a chronological key that is guaranteed to be unique across all clients, even in cases where some clients may have temporarily lost their network connection while they're adding data. These push IDs are not as readable as your array indices, but they are the recommended way of adding items to a list.
That said; you're not dealing with any list here, it is a list of users. If you're using Firebase Authentication to manage the user accounts and handle authentication, the users come with a build in id called uid. In such a case it makes more sense to store the items under their natural key, so under their uid in this case.

Yes there is.
Here is a code from firebase docs of an example of Push().
var messageListRef = firebase.database().ref('message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({
'user_id': 'ada',
'text': 'Example of text.'
});
You can find all this information about other methods here :
https://firebase.google.com/docs/reference/js/firebase.database.Reference

Related

How to fix 'Array.push is not a function' error in Javascript

Im trying to create a small database with localstorage for a small project ( just to emulate a login ).
It's supposed to open two prompts to ask username and password and then store it in a Array of Objects. What happens is that I iniciate the first element of the Array with an Object of an admin and when after inserting the second user (it lets me add one more after the admin) it says that the Users(Array).push is not a function.
var name = prompt('Insert your name');
var password = prompt('Insert your password');
if(localStorage.length!==0){
Users=localStorage.getItem('Users');
}else {
var Users = [{
name:'admin',
password:'admin'
}];
}
var person = {
name:name,
password:password
}
Users.push(person);
localStorage.setItem('Users',Users);
Its supposed to store users and passwords as object inside the array as I load the page over and over again.
Thank you in advance for anyone willing to help
localStorage stores key/value pairs, but the value is stored as strings, not other data structures.
localStorage.setItem('Users', JSON.stringify(Users));
and then when you get it:
Users = JSON.parse(localStorage.getItem('Users'));
You are having an error because when you get it from localStorage it's not an Array.

Why is firebase creating a random identifier between parent and child?

I'm playing around with a firebase web app and having some difficulty diagnosing where something is coming from.
I am trying to simply push some data to my project under the heading of the uid created when authentication takes place. The authentication works fine and it is returning the uid correctly however, when values are passed it seems to be adding a second layer before the actual values.
function registerAccount() {
var firebase = app_firebase;
var firebaseRef = app_firebase.database(); //database reference
var user = firebase.auth().currentUser;
uid = user.uid;
var ref = firebaseRef.ref('User').child(uid); //referencing node
var userName = document.getElementById("txtUsernameInput").value;
if (user) {
// User is signed in.
var data = { //data being added
Username: userName,
}
window.location = 'myHome.aspx';
} else {
// No user is signed in.
console.log("Cannot get UID");
}
ref.push(data);
}
I am expecting the data entry to show with the child of user to be the uid taken from the authentication (this is working) then have the passed values immediately in the uid without the seemingly auto generated child between the uid and the values.
Image shows the unwanted field being generated
[See here][1]
André Kool's suggestion in a comment:
Change ref.push(data); to ref.set(data);
worked.

How do you get specific firebase data without knowing the unique id?

I have some data in my firebase database that I want to retrieve. I did one big push so that all instances would have a unique id. I know want to retrieve this data
I know I can do this:
var gymData = firebase.database().ref('gymData/previousWorkouts')
but when I get returned data like this:
how the hell am I suppose to access that id without knowing it?
for example a user of my app is going to search for an exercise and update it. they search by name, how do I find that id and look inside there? I don't get it :/
firebase.database().ref('gymData/exrcises').orderByChild('name').equal("barbell bench press").once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;//this is id
});
});

Querying firebase database to retrieve user name

I am working on firebase for the first time. I am confused in querying the database. I have two objects on the database, one is the Auth and second one is the Chats. In Auths I have number of UID(user id) nodes, each of these nodes have their respective username. What I am trying to do is, I want to query that Auth object and get all the usernames which is equal to the one I take from a user through input box. In my sql it will be simple as SELECT * FROM auth WHERE username = userInputValue. I need same query like this, Below is what I have done so far.
var _firbaseDB = firebase.database(),
_firebaseAuthRef = _firbaseDB.ref("Auth/");
$("body").on("submit",".search-from",function(e){
e.preventDefault();
var ev = e.target,
_allUsers = $(ev).serializeArray()
_user = _allUsers[0].value;
_firebaseAuthRef.equalTo(_user).on("child_added",function(res){
console.log(res.val());
})
})
You were almost there. What's missing is that you need to specify which attribute you're querying on:
_firebaseAuthRef.orderByChild("n").equalTo(_user).on("child_‌​added",function(res)‌​{
console.log(res.val());
})
More info on the Firebase Database Documentation.

Search inside objects javascript

I'm experimenting on login with firebase. I can make an account, and it'll store additional information too. The problem is retrieving this information.
I can get it using:
usersRef.on("value", function(snapshot) {
console.log(snapshot.val())
}, function (errorObject) {...});
When I do this I get two things (because I have two accounts):
-JrrzEOqZQU0HVeYVXCm: Object, has uid: "simplelogin:21" inside of it
-JrrzgOgQY2z6tNYN0BY: Object, has uid: "simplelogin:22" inside of it
Inside of the second object is the info that I need:
I received simplelogin:22 from the login.
Is there a way I can search inside of the objects to their uid, and get the rest of the information stored inside of that object?
Here's a fiddle
var thisAuthData = authData.uid;
//console.log(authData)
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users");
usersRef.on("value", function(snapshot) {
for(var amount in snapshot.val()){
console.log(snapshot.val()[amount].uid);
//here some if statement thingy's to check with your authData but you can do that yourself I guess ;)
}

Categories

Resources