AngularFire2 - 在更新之前检查对象是否存在

AngularFire2 - check if object exists before update

假设我正在收集一个用户名,我想检查这个用户名是否已经存在于我的 Firebase 数据库中。 AngularFire2 updateset 方法实际上并不检查对象是否存在,但如果存在则替换它。有没有办法检查并说 return 一个可观察到的错误?

目前我的解决方案是检索对象,如果有结果,我知道它存在。我正在寻找一种更直接的方法来检查它。

我需要将其作为数据库对象来执行,而不是身份验证中的实际用户。

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: 'johndoe@example.com',
         password: '!@#34'
     })
   }
});

Firebase 交易

Firebase 针对这种情况提供了 transaction 方法。

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.

如果该值不存在,那么您只需 return 您之前通过 update 发送的值。

this.af.database.object('/users/' + newUser.name).$ref.transaction(currentValue => {
  if (currentValue === null) {
    return {email: 'johndoe@example.com', password: '!@#34'};
  } 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
});

请务必注意,这是来自 Firebase API(而非 Angularfire2)的方法,但您仍然可以通过调用 $ref.

来访问这些方法

我知道这是一个老问题,但我在使用 AngaularFire4 时遇到了类似的问题,所以发布此问题以帮助其他人:

this.db.object(`/users/${uid}`).first().subscribe(x => {
    if (x.$exists()){
          console.log(`FOUND`,x);
    }else {
          console.log(`NOT FOUND`);
    }
});
}
 this.realtimedbService.getOneItem(key,  'colection').valueChanges()
              .subscribe(
                  result => {
                      if (result === null) {
                          console.log('NOT EXIST');

                                     }
                      if (result !== null) {
                        console.log('EXIST');
                        /// PUT YOUR UPPDATE METHODE HERE

                      }
                  },
                  error => {
                      console.log(" EE : ");
                      console.log(error);
                  }
              );