Hello, I am trying to check if a data exists in the firebase realtime database But i keep getting an error saying that it does not exists.
check(){
var checkRef = firebase.database().ref('users');
checkRef.once('value', function(snapshot) {
if(snapshot.val().hasOwnProperty('referralCode')) {
console.log("Referral Code exist.");
}
else {
console.log("Referral Code does not exist.");
}
});
}
^this is my code
Try something like…
check(){
const checkRef = firebase.database().ref('users');
checkRef.once('value', (snapshot) => {
if(snapshot.val().hasOwnProperty('referralCode')) {
console.log("Referral Code exist.");
}
else {
console.log("Referral Code does not exist.");
}
});
}
You might be running into scope issues with the function keyword.
It does not work, I still get referral code does not exist
Well work off of what you actually get in the snapshot. What is the value? Kind of hard to know the right solution if you don’t know what the value being returned looks like.
I managed to find the solution `
check(){
firebase.database().ref('users/').once('value', (snapshot) => {
snapshot.forEach(snap => {
this.newlist.push(snap.val().referralCode);
if(this.checking.referralCode == snap.val().referralCode){
console.log('Referral Code Exists')
this.presentAlert();
this.auth.onAuthStateChanged(se => {
this.fire = firebase.database().ref('users/' + se.uid).on('value', resp => {
this.afDB.object('users/'+ se.uid).update({
point: this.data.point + 50,
})
console.log(resp)
})
})
}
})
})
}`
however, im trying to add points to my firebase database but because it is in a loop, it added more than 50 points
You can do this in a very simple way
This.database.collection(“collectionname”,querry=>querry.where(“data”,"=",checkyourfield).subscribe(res=>{
If(res.length<1)
Data donot exist
Else
It exists )
// in simple an array will he returned so you can check if it is empty or not other way of doing this is use get instead fo valuechanges and instead of res.length use res.exists
This is a very simple way there are many alternate ways too
can this be use for realtime database? Because if I remember correctly, collection is used for firestore
Write firebase.database instead od collection