Google Firebase: snap.val().username returns undefined - javascript

I get the item in the realtime database where the email child equals the email in the localStorage and that works just fine.
however when i try to log the username, it returns undefined instead of the actual username
let useremail = localStorage.getItem("useremail")
firebase.database().ref("/users").orderByChild('email').equalTo(useremail).on("value", function(snap){
let data = snap.val();
console.log(data.username)
})
Anyone knows how to fix this?
database looks like this
If i log data this shows:
and If i log useremail the correct string does show

Try this:
let useremail = localStorage.getItem("useremail")
firebase.database().ref("/users").orderByChild('email').equalTo(useremail).on("value", function(snap){
snap.forEach(function(childSnapshot)){
let data = childSnapshot.val();
console.log(data.username)
});
});
Since reference is at node users then you need to loop to be able to access the attributes.

Related

Can someone explain where the "messages" key comes from?

I am following a tutorial and I understood everything up until everything beyond where I declared the let variable.
function submitMessage(event) {
event.preventDefault();
const email = document.getElementById("email").value;
const fullName = document.getElementById("fullName").value;
const feedbackType = document.getElementById("feedbackType").value;
const comment = document.getElementById("comment").value;
const messageObject = {
email,
fullName,
feedbackType,
comment
};
let currentMessages = [];
if (window.sessionStorage.getItem("messages")) {
currentMessages =
JSON.parse(
window.sessionStorage.getItem("messages")
);
}
currentMessages.push(messageObject);
window.sessionStorage.setItem(
"messages",
JSON.stringify(currentMessages)
);
}
You're setting the "messages" key for the session storage here:
window.sessionStorage.setItem(
"messages", // arbitrary key name
JSON.stringify(currentMessages) // value to store for this key
);
let currentMessage is an empty array that will hold messageObject variable expressed few row before.
After currentMessage there is a step that setup a session store that we going to call "messages".
The window.sessionStorage function is used to save some data inside the browser, in our case currentMessage. In this way if your refreshed the browser page you will able to get the last data save in window.sessionStorage.
So in the first step this function try to get messages object from the session storage that we have e called messages.
Then, one fetched it will push the currentMessage inside it with setItem, so after you reload the browser you will be able to retrieve the array passing through the session storage getItem and to get this value it need to search inside some key and the key is messages, in other word the key in the session storage that can hold our array.

displaying local storage values

I am trying to display only the values which are saved inside of the local storage and not the key value which will show all the data in the local storage after the login form has been submitted
welcome <span id="demo"></span>
<script>
document.getElementById('demo').innerHTML=localStorage.getItem ("users") === ("username");
</script>
Please try this.
let userData = localStorage.getItem ("users") ;
if(userData) {
userData = JSON.parse(userData);
document.getElementById('demo').innerHTML = userData[0]['username'];
}
Hope this will solve your problem.
Ok first of all, you really should not save the password in your localStorage.
The user (Not users) should be an object that is holding ONLY public information that you don't mind even other websites to have access to.
And it should be something like {username: "Something", email: "something#tada.com"}
By that you can use it like this:
let user = localStorage.getItem('user');
if (user) {
user = JSON.parse(user);
document.getElementById('demo').innerHTML = user.username;
}

Referencing firebase database with a variable and string concatenation

As you can see below i'm trying to read a list of data from the database and then loop over the result, in javascript. The function runs whenever i open/refresh the page:
firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
snapshot.forEach(function(e) {
var element = e.val();
var roomId = element.Id;
});
});
However, that string concatenation to specify the User Id doesn't work for some reason. When i replace it with the user Id directly like this:
firebase.database().ref("Users/GR3JFsMrKOjCrLhDNFMaq72COd07/rooms").on.....
that works fine. But of course i want to use the variable which contains the Id of the current user.
The uid variable is assigned a value in the onAuthStateChanged when checking if the user is signed in:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
uid = user.uid;
If I add a console.log like this:
firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
console.log(snapshot.parent);
snapshot.forEach(function(e) {
the output with the first code example (using uid variable) is: undefined.
If i specify the User Id directly it is: room-id-1 (the result i want).
How do i make the string concatenation work? Or is this the wrong way of specifying the path of the current user?
It is extremely unlikely that the problem is in the string concatenation itself. It is much more likely that uid simple doesn't have a value yet when you start reading from the database.
To make sure the uid is available, put the reading of the data into the auth state listener like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
uid = user.uid;
console.log("uid="+uid);
firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
snapshot.forEach(function(e) {
var element = e.val();
var roomId = element.Id;
console.log("roodId="+roomId);
});
});
}
})

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

Get json array from sub mongoose query

I have a sub query in mongoose need to get array out of sub query and attach to main json out put/ object.
my first query get user info which contains blocked_users array which is nothing but array of user id's.
i my second query we get profile details of blocker_users array and append to main user object in blocked_users.
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
var blcked_contacts;
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
//blcked_contacts.push(blocked_users);
console.log(blocked_users);
return;
};
/*else{
blcked_contacts = [];
}*/
});
userInfo['blocked_contacts'].push(blocked_users);
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
//userInfo['blocked_contacts'].push(blcked_contacts);
//userInfo['blocked_contacts'] = user.blocked_contacts;
var userData = Array();
}
});
Don't really know what you're looking for. But saw a problem in your code. You've assigned the blocked_users to the blocked_contacts field outside the find method.
Since these calls are asynchronous in nature, it might happen that the assignment takes place even before the documents are fetched from MongoDB. So you should write your assignment statements inside the find methods' callback, just the way Medet did.
Noticed few mistakes in your code like trying to use .push on an object. You cant do
userInfo['blocked_contacts'].push(blocked_users); // incorrect as userInfo is an empty object and you dont have an array defined for userInfo['blocked_contacts']
You probably get cannot push into undefined error for this. So instead do
userInfo['blocked_contacts'] = blocked_users;
Also you have to do this inside the second find() as blocked_users is only available inside it. So your final query should be something like
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = blocked_users; // assign blocked_users into userInfo
console.log(userInfo) // Your required object
} else {
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = []; // assign null array if no blocked users fould
}
});
var userData = Array();
}
});
The result of console.log should be an object like this
{
user_id : "..id of searched user...",
country_code : "..country code of searched user..",
blocked_contacts : [<array containing detais of all blocked users>] // null array if no users found
}

Categories