I am trying to read the "total_event_created" value of the following data.
This is part of my code.
var userId = firebase.auth().currentUser.uid;
return database.ref('users/' + user_id).once('value').then(function(snapshot) {
var total_event_counter = snapshot.val().total_event_created;
console.log("total_event_counter",total_event_created);
});
});
I want the value to then use it for reference.
database.ref('events/' + user_id + total_event_created).set({ stuff here });
The problem is that I am getting this message in the console.
try something along the lines of:
var userId = firebase.auth().currentUser.uid;
return database.ref('users/' + user_id).once('value').then(function(snapshot) {
return total_event_counter = snapshot.val().total_event_created;
}).then(function(tec) {
console.log(tec);
});
});
Related
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);
});
});
I am new to Ionic / Firebase and I try to update fields via a form. Everything works, no error, all console log show up what needed but the data are not being updated in the database.
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
function writeUserData(name, description) {
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
}
$state.go("tab.account");
});
Any idea ? Or maybe a better method to simply update firebase's database via a form when the user is logged in ?
Seems you didn't really don't know the real significance/uses of function yet about when to use it
Well it's because you wrap it inside writeUserData and which is you didn't event execute/call this function
Also function writeUserData isn't necessary in this situation
so remove function it
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var saveButton = document.querySelector('#save');
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
});
});
You just transfer $state.go("tab.account"); to receiveNewData
Edited
To be able to catch the changes just call add child_added event listener inside 'accounts/' + userId
function receiveNewData() {
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
I'm having a problem saving data to firebase, because my data only updates the data already in the database, it does not insert new data. That is when I create a new user and it solves an exercise when trying to fetch this data in the firebase it returns me this error.
FIREBASE WARNING: Exception was thrown by user callback. TypeError: Can not convert undefined or null to object.
function writeUserData(userId, data) {
var key = Object.keys(data)[0];
var values = Object.values(data)[0];
console.log(values);
firebase.database().ref('users/' + userId + '/' + jsData.topicId + '/' + key).set({
topic_log: values
});
}
take a look to this code right here :
function go() {
var userId = prompt('Username?', 'Guest');
checkIfUserExists(userId);
}
var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
function userExistsCallback(userId, exists) {
if (exists) {
alert('user ' + userId + ' exists!');
} else {
alert('user ' + userId + ' does not exist!');
}
}
// Tests to see if /users/<userId> has any data.
function checkIfUserExists(userId) {
var usersRef = new Firebase(USERS_LOCATION);
usersRef.child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userExistsCallback(userId, exists);
});
}
You can use the exists() method of the data snapshot to check for data.
For example:
var userRef = firebase.database().ref('users/' + userId);
userRef.once('value', function(snapshot) {
if (snapshot.exists){
console.log('user exists');
}
});
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);
});
});
In my AngularJS controller, I have the following code:
$scope.readMDB = function () {
var fs = require('fs');
var adodb = require('node-adodb');
var password = document.forms["mdbSelForm"]["pwd"].value;
var revSQL = fs.readFileSync('revenue.sql', 'utf-8');
revSQL = revSQL.replace(/(\r\n|\n|\r)/gm, " ");
revSQL = revSQL.replace(/[รค]/g, function () { return unescape("%E4") });
$scope.revenueSQL = String(revSQL);
console.log("revSQL: " + $scope.revenueSQL);
connection = adodb.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + $scope.selectedMDB + ';Jet OLEDB:Database Password=' + password + ';');
// debug
adodb.debug = true;
connection
.query($scope.revenueSQL)
.on('done', function (data) {
var revAll = JSON.stringify(data);
var revenueData = JSON.parse(revAll).records;
fs.writeFile('./model/revenue.json', JSON.stringify(data), function (err) {
if (err) throw err;
console.log("revenue.json saved");
});
return true;
})
.on('fail', function (data) {
return false;
});
}
A similar code worked fine while not using Angular. Now, it doesn't work no more, because of the
connection.query($scope.revenueSQL)
part. More precisely, the $scope.revenueSQL is not recognized as the SQL Statement that it actually is. Putting the SQL directly, without reading it from a file, works fine. Still, looking at my console, I see that $scope.revenueSQL is exactly what I want. But being put as parameter into .query(), something seems to go wrong. Any ideas?
Try
$scope.revenueSQL = $scope.$eval(String(revSQL));
to execute the expression on the current scope and returns the result.