Update an existing value in Firebase Realtime Database - javascript

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

Related

Listening query with data filtering

I have this structure
comments:
- FG1MaPfTFsdgdsgsruL9Cgx5sY2
+ content
+ value: "My comment"
+ creator: "0U1MaPfTF2fwcgqWuruL9Cgx5sY2"
+ date_create: "2015-02-21T12:40:35Z"
+ users[]
+ CByXgSgB4khZ5LgugXGRdfK7CLk2
+ XakJ8zn711bUeSpCK1ss7Fsz7JX2
+ relations[]
+ HTyXgSgB4khZ5LgugXGRdfK7CLk2
+ CakJ8zn711bUeSpCK1ss7Fsz7JX2
+ settings[]
+ duration: 2
How to write the appropriate query listening in the application so that when the user UID appears in users[] it will immediately receive a message.
An additional filter will be time in duration
First get the user uid:
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
let database = firebase.database();
let userRef = database.ref("users").orderByKey().equalTo(uid);
userRef.on('value', ((snapshot) => {
if(snapshot.exists()){
console.log(snapshot.val());
}
});
}
Try the above, first retrieve the uid then add a reference to node users and using orderByKey() you can query on the uid, and then using exists() you can check if it exists in the database or not.

How to check if usernames are unique in Firebase

I have a function (not finished yet) that should check if a username already exists/is unique in my Firebase database. I have searched Google on how to implement this and I have managed to get the below. Unfortunately, it doesn't work and I don't even get any console.logs. Any help is appreciated - what exactly am I doing wrong?
onChangeUsername = (event) => {
var oldError = {...this.state.error};
firebase.database().ref().child("Usernames").orderByValue().once('value', (snapshot) => {
var exists = (snapshot.val() !== null);
console.log(exists);
console.log("hello");
});
if(this.state.validation.username.unique===true)
{oldError.username = "This username is already taken"}
else if((event.nativeEvent.text.length<this.state.validation.username.min) || (event.nativeEvent.text.length>this.state.validation.username.max) )
{oldError.username = "Username should be between " + this.state.validation.username.min + " and " + this.state.validation.username.max + " characters" ;}
else oldError.username = "";
this.setState({ username: event.nativeEvent.text, error:oldError })
}
my database structure is as follows:
Database:{ Usernames: {uid1: username1, uid2: username2}}
****Question Update ****
After Comments from Frank, I have changed my code to the following. It still doesn't work, but my he has spotted a couple of errors that needed fixing:
onChangeUsername = (event) => {
var oldError = {...this.state.error};
firebase.database().ref().child("Usernames").orderByKey().equalTo("Username1").once('value', (snapshot) => {
var exists = (snapshot.val() !== null);
console.log(exists);
console.log("hello");
});
if(this.state.validation.username.unique===true)
{oldError.username = "This username is already taken"}
else if((event.nativeEvent.text.length<this.state.validation.username.min) || (event.nativeEvent.text.length>this.state.validation.username.max) )
{oldError.username = "Username should be between " + this.state.validation.username.min + " and " + this.state.validation.username.max + " characters" ;}
else oldError.username = "";
this.setState({ username: event.nativeEvent.text, error:oldError })
}
and my database to the following:
Database:{ Usernames: {Username1: uid1, Username2: uid2}}
You're missing a comparison in your query:
firebase.database().ref().child("Usernames").equalTo("Username1").orderByValue()
I recommend btw inverting the data structure. If you want user names to be unique, use those as the keys in the parent node:
Database:{
Usernames: {
Username1: uidOfUserWithUsername1,
Username2: uidOfUserWithUsername2
}
}
This way your lookups will be simpler and fast, since you don't need a query. In addition, the value will now allow you to easily look up more information on the user who claimed this user name.

Angularfire Increment transaction

Im having trouble incrementing a count of post "likes". The following is what I have right now:
addLike(pid, uid) {
const data = {
uid: uid,
};
this.afs.doc('posts/' + pid + '/likes/' + uid).set(data)
.then(() => console.log('post ', pid, ' liked by user ', uid));
const totalLikes = {
count : 0
};
const likeRef = this.afs.collection('posts').doc(pid);
.query.ref.transaction((count => {
if (count === null) {
return count = 1;
} else {
return count + 1;
}
}))
}
this obviously throws and error.
My goal is to "like" a post and increment a "counter" in another location. Possibly as a field of each Pid?
What am I missing here? I'm certain my path is correct..
Thanks in advance
You're to use the Firebase Realtime Database API for transactions on Cloud Firestore. While both databases are part of Firebase, they are completely different, and you cannot use the API from one on the other.
To learn more about how to run transactions on Cloud Firestore, see updating data with transactions in the documentation.
It'll look something like this:
return db.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(likeRef).then(function(likeDoc) {
if (!likeDoc.exists) {
throw "Document does not exist!";
}
var newCount = (likeDoc.data().count || 0) + 1;
transaction.update(likeDoc, { count: newCount });
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});

How to verify if data exist in Firebase

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

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