在Cloud Firestore中检查文档字段以查找特定值

时间:2018-03-19 20:49:56

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

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

也许有人已经有反应表单验证的片段了吗?

3 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分: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 :(得分:0)

在我的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()
}