Let's say I'm collecting a username, and I want to check if this username already exists in my Firebase database. AngularFire2 update
or set
methods don't actually check if the object exists, but replaces it if so. Is there a way to check that and say return a observable error?
Currently my solution is to retrieve the object and if there are results, I know it exists. I'm looking for a more straightforward way to check that.
I need to do that as a database object, not an actual user in Authentication.
let userExists = false;
this.af.database.object('/users/' + newUser.name).subscribe( user => {
if (user) {
userExists = true;
console.log('This username is taken. Try another one');
}
else {
this._af.database.object('/users/' + newUser.name).update({
email: '[email protected]',
password: '!@#$1234'
})
}
});
Firebase provides a transaction method for this situation.
transaction()
is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.
If if the value is not present, then you just return the value you previously sent via update
.
this.af.database.object('/users/' + newUser.name).$ref.transaction(currentValue => {
if (currentValue === null) {
return {email: '[email protected]', password: '!@#$1234'};
} else {
console.log('This username is taken. Try another one');
return Promise.reject(Error('username is taken'))
}
})
.then( result => {
// Good to go, user does not exist
if (result.committed) {
// TODO: Take additional action
}
})
.catch( error => {
// handle error
});
It's important to note that this is a method from the Firebase API (not Angularfire2), but you can still access those methods by calling $ref
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With