【问题标题】:Check a document field for a specific value in Cloud Firestore检查文档字段中 Cloud Firestore 中的特定值
【发布时间】:2018-08-28 13:20:44
【问题描述】:

我想使用自定义用户名创建用户注册。我将用户的用户名存储在 Firestore 的用户文档中。如何验证用户集合中是否已存在用户名?

也许有人已经有 sn-p 用于响应式表单验证?

【问题讨论】:

  • 尝试获取它where username== usernameVariable,如果有结果,则该用户名已经是数据库中的用户名。你应该使用 firebase.auth。

标签: angular firebase google-cloud-datastore google-cloud-firestore angularfire2


【解决方案1】:

这里是角码:

 fs_collection: AngularFirestoreCollection<UserItems>;

 this.db.collection<UserItems>('Users’).ref.where('username', '==',
 this.model.username).get().then((ref) => {

             let results = ref.docs.map(doc => doc.data() as UserItems);
             if (results.length > 0) {
                console.log(userData); //do what you want with code
            }
             else {
                 this.error(“no user.”);
             }
         });

【讨论】:

    【解决方案2】:

    在我的 Angular/Ionic 项目中,我使用异步验证器来检查存储为用户集合中用户文档字段的现有用户名。在我的构造函数中,我有:

    this.signupForm = formBuilder.group({
      username: ['', Validators.compose([Validators.required, 
                                         Validators.minLength(2),
                                         Validators.maxLength(24), 
                                         this.asyncValidator.bind(this)],
      password: ['', Validators.compose([Validators.minLength(6), 
                                         Validators.required])]
    })
    

    我的 asyncValidator 方法:

    asyncValidator(control) {
      let username = control.value
      return new Promise(resolve => {
        this.checkUsername(username).then(snapshot => {
          if(snapshot.docs.length > 0){
            resolve({
              "username taken": true
            });
          } else {
            resolve(null);
          }
        })
      })
    }
    

    我对 Firestore 的查询:

    checkUsername(username) {
      return firebase.firestore().collection('users').where("username", "==", username).get()
    }
    

    【讨论】:

      【解决方案3】:

      没有有效的方法来检查集合中的所有文档的特定值。您必须依次阅读每份文件,并检查它们。从性能和成本的角度来看,这都是令人望而却步的。

      您可以做的是创建一个额外的集合(通常称为反向索引或反向映射),在其中您使用用户名作为文档的名称,并且(例如)用户的 UID 作为文档的数据.然后,您可以轻松检查checking for the existence of a document with that specific name 是否已使用用户名,这是一种直接访问查找,因此具有高度可扩展性。

      由于您使用google-cloud-datastore 标记;如果您确实也在寻找该数据库的答案,请查看Unique email in Google Datastore。

      【讨论】:

        猜你喜欢
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 2018-03-16
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多