How to verify if data exist in Firebase - javascript

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

Related

Firebase Functions - Return after Realtime Database fetched inside User Fetch

I have a Firebase Cloud Function that is called in my app with JavaScript.
When the function is called it fetches the user data from the user ID, then fetched a record from the Realtime Database to check for a match.
This function works but is returning "null" and finishing early instead of returning the success or error message when the match is detected.
How can I make the return text be the success or error from the match and only complete once this match is decided?
exports.matchNumber = functions.https.onCall((data, context) => {
// ID String passed from the client.
const ID = data.ID;
const uid = context.auth.uid;
//Get user data
admin.auth().getUser(uid)
.then(function(userRecord) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("path/to/data/" + ID);
return ref.on("value", function(snapshot) {
//Fetch current phone number
var phoneORStr = (snapshot.val() && snapshot.val().phone) || "";
//Fetch the current auth user phone number
var userAuthPhoneNumber = userRecord.toJSON().phoneNumber;
//Check if they match
if (userAuthPhoneNumber === phoneORStr) {
console.log("Phone numbers match");
var updateRef = db.ref("path/to/data/" + ID);
updateRef.update({
"userID": uid
});
return {text: "Success"};
} else {
console.log("Phone numbers DO NOT match");
return {text: "Phone number does not match the one on record."};
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
return {text: "Error fetching current data."};
});
})
.catch(function(error) {
console.log('Error fetching user data:', error);
return {text: "Error fetching data for authenticated user."};
});
});
Thank you
The Firebase ref.on() method doesn't return a promise, so the return statements you have in there do nothing.
You're looking for ref.once(), which returns a promise, and thus will bubble up the return statements you have within it:
return ref.once("value").then(function(snapshot) {
...
As Doug pointed out, you'll also need to return the promise from the top level. So:
//Get user data
return admin.auth().getUser(uid)
.then(function(userRecord) {

Update an existing value in Firebase Realtime Database

I want to add to an existing value in Firebase
I have an updatePoints function that looks up a user, if they already exist I want to lookup up the existing points and add the newPoints value. How can I do this with the below please?
updatePoints(userID, newPoints){
firebase.database().ref('/userProfile').child(userID).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
if (exists) {
console.log('user ' + userID + ' exists!');
firebase.database().ref('markets/'+userID).update({
points: newPoints // I want to look up eixsitg points and add on newPoints,
});
} else {
console.log('user ' + userID + ' does not exist!');
firebase.database().ref('/markets').child(userID).set({
points: 1
});
}
});
Worked it out, if this helps someone...
console.log("val",snapshot.val().points);

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

How do I read correctly from a firebase database?

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

Firebase data is not updated properly

The problem : the data always get updated into 4350,
And the alert keep's pop-up-ing.
The code:
// Get no antrian function
function getNoAntri(tipe, username, name) {
// Define firebase URL
var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Log firebase URL
console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Warn user that this fiture need internet
alert('Fitur ini membutuhkan internet untuk mengambil data');
// Confirmation
alert("Mohon konfirmasi ulang");
var nama = prompt("Masukan nama"),
nik = prompt("Masukan NIK:");
if (nama != "" || nik.length != 16) {
var pasien = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + '/pasien/');
// Initialize data
faskesRef.on("value", function(snapshot) {
// Update variables
var data = snapshot.val().antrian,
one = 1,
sum = data + one;
// Update nomor antrian
faskesRef.update({
nama: name,
antrian: sum
});
// Print data
alert('No antrian: ' + snapshot.val().antrian);
// Push data to firebase
pasien.push().set({
nama: nama,
nomor_antrian: snapshot.val().antrian
})
});
} else {
// Error message
alert("Input anda tidak valid. \n Anda tidak bisa mendapatkan nomor antrian");
}
}
I've try many ways, but the code still never work.
Sorry If I doesn't ask a proper question btw
It's a bit unclear what your problem is, but an educated guess is that it boils down to this fragment of your code:
// Push input value to firebase
pasien.push().set({
nama: nama,
nik: nik,
lokasi: lokasi
});
window.location.href = 'option/' + 'available.html';
Writing data to Firebase is an asynchronous operation. Calling set() starts that operation, but by the time the set window.location, the write operation won't be done yet.
The solution is to wait for the write operation to complete before navigating away, which you can do by using a Firebase completion listener:
// Push input value to firebase
pasien.push().set({
nama: nama,
nik: nik,
lokasi: lokasi
}, function(error) {
if (!error) {
window.location.href = 'option/' + 'available.html';
}
else {
// TODO: handle error
}
});

Categories