Firebase custom query - javascript

How to get the value of Inmate_DOB from the below structure of Firebase Web API.
Please find the snap below :
I tried the below code is it right to handle, But I didn't retrieve the value.
GetInmate.Js
angular.module('starter.InMateIdContactDetailsController', ['firebase'])
.controller('InMateIdContactDetailsCtrl', function($scope,$rootScope,$filter,$ionicLoading,$state,$window, $cordovaSQLite,$cordovaCamera,$firebase,$firebaseAuth,$firebaseArray) {
var userId = firebase.auth().currentUser.uid;
var ref = firebase.database().ref().child("Tables/Inmate_Data");
$scope.InMatedata = $firebaseArray(ref);
if(!$scope.InMatedata){
alert('Records not found Auth!');
}else{
alert('Records found! Auth');
}
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
var userID = user.uid;
firebase.database().ref('Tables/Inmate_Data/'+userID).once('value').then(snapshot => {
const userDOB = snapshot.val().Inmate_DOB;
alert(userDOB);
alert(test);
})
}
});
});

I think you are just missing a / in your original code after 'Tables/Inmate_Data'.
return firebase.database().ref('Tables/Inmate_Data/' + userId).once('value')
.then(function(snapshot) {
var Inmate_dob = snapshot.val().Inmate_DOB;
alert(Inmate_dob);
}

Instead of using firebase.auth().currentUser.uid, you might want to use onAuthStateChanged(), this way you can always be sure that the code inside the block will only be executed if the user is actually logged in otherwise firebase.auth().currentUser might return null. If you have made sure that this value is not null, then you can do something like this:
var userID = firebase.auth().currentUser.uid; //Current User UID
firebase.database().ref('Tables/Inmate_Data/'+userID).once('value').then(snapshot => {
const userDOB = snapshot.val().Inmate_DOB;
alert(userDOB);
});
To avoid getting null, you can put the above code inside onAuthStateChanged
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
var userID = user.uid;
firebase.database().ref('Tables/Inmate_Data/'+userID).once('value').then(snapshot => {
const userDOB = snapshot.val().Inmate_DOB;
alert(userDOB);
});
}
});
If you want to retrieve the date of birth of all users, then you can do something like this:
firebase.database().ref('Tables/Inmate_Data').on('child_added', snapshot => {
firebase.database().ref(snapshot.key+'/Inmate_DOB').on('value', snap => {
const userDOB = snap.val();
alert(userDOB);
});
});

Related

Firebase Web Read from Real-Time Database

I'm trying to display the user's price that they entered in the database, but I'm getting "undefined' back instead of the value that was entered. I didn't get any errors in the console either. How can I fix this? I am using HTML, JavaScript, and CSS. I have provided a screenshot and my code.
Studio Dashboard JavaScript code:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const database = firebase.database();
const auth = firebase.auth();
//const auth = getAuth();
firebase.auth().onAuthStateChanged((user) => {
if (user) {
readData();
// ...
} else {
window.location.href = "login.html?error";
alert("No active user please sign or sign up.");
}
});
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot => {
// Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
// Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}).catch(e => { console.log(e) })
}
function updatePrice() {
// Get data
numberInput = document.getElementById("numberInput").value;
const user = firebase.auth().currentUser;
// Enter database location
firebase
.database()
.ref('/studiopick/studio/users/' + user.uid + "/prices/roomA/serviceOne")
.update({
//studioName : studioName,
numberInput: numberInput,
});
}
You should use the on method instead of get
function readData() {
const user = firebase.auth().currentUser;
database.ref('/studiopick/studio/users/' + user.uid).on('value', (snapshot) => {
//Tab One Display
document.getElementById("studioName").innerText = snapshot.val().studioName;
document.getElementById("profile-name").innerText = snapshot.val().studioName;
document.getElementById("firstName").innerText = snapshot.val().firstName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("lastName").innerText = snapshot.val().lastName;
document.getElementById("email").innerText = snapshot.val().email;
document.getElementById("phoneNumber").innerText = snapshot.val().phoneNumber;
//Tab Two Display
document.getElementById("servicePrice").innerText = snapshot.val().numberInput;
}, (e) => { console.log(e) })
}

Retrieving Firebase Child Value in Javascript

function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid);
if (adaRef.orderByChild("Role").equalTo("admin")) {
location.href = "DB.html";
} else {
location.href = "index.html";
}
}
I would like to link my "admin" account to DB.html and "user" account to index.html but i think i always failed in Retrieving the Child Value.
You're not retrieving the data from the server. Remember you need to call .once('value') to get your query and then iterate through the remaining code based onw hether their value is of admin or user. Firebase Docs has more explination I've amended your code and put it below
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
return snapshot.forEach(snapshot=>{
if (snapshot.child("Role").val()==="admin") {
location.href = "DB.html";
} else {
location.href = "index.html";
}
return console.log("added");
})
})
}
If you just wanted to find out who was of the user type admin...i'd use this below...much more efficient.
function sontinue() {
var user = firebase.auth().currentUser;
var uid = user.uid;
var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
//you now need to retrieve the data
return adaRef.once('value').then((snapshot)=>{
//you now have all the users that are just admins
return snapshot.forEach(snapshot=>{
location.href = "DB.html";
return console.log("added");
})
})
}

read a users UID from Firebase

I'm trying to read in uid into a var but for some reason it does not work. My database is:
if (user) { // User is signed in!
var uid = user.uid;
var refreshToken = user.refreshToken;
firebase.database().ref().child("owners").orderByChild("uid").equalTo(uid).on('value', function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var controller=childSnapshot.val().name;
console.log('controller is: ' + controller);
});
});
my console.log statement never shows to the console. Any help would be appreciated as the really has me stumped right now.
try this:
firebase.database().ref().child("owners").child("Pellet_Pirate_1").child("details").orderByChild("uid").equalTo(uid).on('value', function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var controller=childSnapshot.val().name;
console.log('controller is: ' + Controller);
});
});

Querying firebase database at onwrite event

I am trying to write a firebase function which will check the the "user" and behave according to that on database write event. However when i query the database it returns null everytime and i didnt figure out what i am doing wrong. Any help is appreciated.
Thanks in advance.
My realtime database structure is like this:
ilk-projemiz-cd55baddclose
users
edRIPg8BcZU9YPbubp7HtQo7phl1
sayilar: 1532
status: "on"
hakan
sayilar: 5000
status: "waiting"
mehmet
sayilar: 7000
status: "on"
My firebase function file is this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = event.data.adminRef.child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value", sorunsuz,sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
function sorunsuz(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}
This line: const events = event.data.adminRef.child('users'); tries to access a users node under the status node. And I think what you wanted to do is access the users node under the root reference.
Use the Admin SDK instead:
const events = admin.database().child('users');
Update: the user variable is out of scope, so I suggest you move the sorunsuz() function to be inside the on() function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sayi = functions.database.ref("/users/{uid}/status").onWrite(event => {
const status = event.data.val();
var user = event.data.ref.parent.key;
if (status =="on") {
console.log(status);
const events = admin.database().child('users');
const query =events.orderByChild('status').equalTo('on').limitToFirst(2);
query.on("value",
function(data) {
console.log("11111");
var fruits = data.val();
console.log(fruits); //it returns null here
var keys = Object.keys(fruits);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if(key==user){
//console.log(fruits[key].sayilar);
console.log("aaa");
}else{
console.log("bbbb");
}
}
}, sorunlu);
}
});
function sorunlu(error) {
console.log("Something went wrong.");
console.log(error);
}
you have to listen to users node
functions.database.ref("/users/{uid}/status"),
this path is not exist anywhere thats why you are getting null.
exports.sayi = functions.database.ref("/users").onWrite(event => {
const status = event.data.val(); //this data will be new
//Use above value to refer things
if (event.data.previous.exists()) {
//Update operation
}
});

event.params.wildcard returning the wrong value

I have a pretty simple firebase function :
exports.sendFollowNotification = functions.database.ref('PendingRequest/{receiver_id}/{sender_id}').onWrite(requestEvent => {
const requestSnapShot = requestEvent.data;
const senderId = requestEvent.params.sender_id;
const targetId = requestEvent.params.receiver_id;
const target_token = requestSnapShot.child('sender').val();
const sender_token = requestSnapShot.child('receiver').val();
console.log('sender_id :'+senderId);
console.log('target_id :'+targetId);
console.log('target_token: '+ target_token);
console.log('sender_token: '+sender_token);
const pendingRequestPayload = {
data: {
token_sender : sender_token,
token_target : target_token,
request_sender : senderId,
request_receiver : targetId,
my_message_id: '0'
}
};
if(target_token != null){
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToDevice(target_token, pendingRequestPayload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
}
Whenever this function fires there are two values that gets swapped : senderId gets targetId value and vice versa. Both values are retrieved with the params property while nothing strange happens to the values i'm getting from requestSnapShot.child('value_name').val();
The dumb solution is just to swap the two values whenever i need them but well, that's a really dumb solution. What am I missing here ?
If "target" is "receiver", these are swapped:
const target_token = requestSnapShot.child('sender').val();
const sender_token = requestSnapShot.child('receiver').val();
Are you doing that intentionally to work around the problem?
Update:
It's hard to guess why this isn't working for you. I copied your code, eliminated your work-around, and shortened it for testing:
exports.sendFollowNotification = functions.database.ref('PendingRequest/{receiver_id}/{sender_id}')
.onWrite(requestEvent => {
const requestSnapShot = requestEvent.data;
const senderId = requestEvent.params.sender_id;
const targetId = requestEvent.params.receiver_id;
const target_token = requestSnapShot.child('receiver').val();
const sender_token = requestSnapShot.child('sender').val();
console.log('sender_id :'+senderId);
console.log('target_id :'+targetId);
console.log('target_token: '+ target_token);
console.log('sender_token: '+sender_token);
});
Ran with this data:
{
"PendingRequest" : {
"R1" : {
"S1" : {
"receiver" : "R-token",
"sender" : "S-token"
}
}
}
}
And got this log output:
sender_token: S-token
target_token: R-token
target_id :R1
sender_id :S1

Categories