运行集合组查询以查看我的Firebase子集合中的字段是真还是假

问题描述 投票:0回答:1

我正在创建一种登录方法,该方法试图在验证他们的电子邮件地址后检查当前用户是否同意我的协议条款。我的功能如下:

SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
        .then(cred => {
            this.ngZone.run(() => {
                // Gets current signed in user.
                this.afAuth.authState.subscribe(user => {
                    // Queries Details subcollection.
            this.db.collection('users').doc(user.uid).collection('Details')
                        .get().toPromise().then(
                            doc => {
                                if (user.termsOfAgreement == false) {
                                    this.router.navigate(['terms']);
                                } else {
                                    this.router.navigate(['dashboard']);
                                }
                            })
                })
            });
        }).catch((error) => {
            window.alert(error.message)
        })
}

我知道我正在获取firebase用户对象,并且它不包含我的特定子集合字段名称(即user.termsOfAgreement)。但是我将如何访问那些?我正在尝试检查我的termsOfAgreement字段是正确还是错误。

注册时我的Firestore用户收藏状态

User (Collection)
- lastLogin: timestamp
- name: string
- userId: string

Details (subcollection)
- termsOfAgreement: false 
javascript firebase google-cloud-firestore angularfire
1个回答
0
投票

首先注意,this.db.collection('users').doc(user.uid).collection('Details')不是集合组查询,但是对单个集合的读取操作。

听起来您想检查用户文档下的Details集合是否包含termsOfAgreement等于true的文档。您可以最轻松地通过以下方法进行检查:

firebase.firestore()
        .collection('users').doc(user.uid)
        .collection('Details').where('termsOfAgreement', '==', true).limit(1)
        .get().then((querySnapshot) => {
            if (querySnapshot.empty == false) {
                this.router.navigate(['terms']);
            } else {
                this.router.navigate(['dashboard']);
            }
        })

上面的代码使用的是常规JavaScript SDK,因为此操作不需要使用AngularFire。但是除此之外,这两种方法都一样:您针对集合触发查询,然后检查是否有任何结果。

除了修复您的代码外,这还通过两种方式对其进行了优化:

  1. 查询已发送到服务器,因此您只传输符合条件的数据。
  2. 最多传送一个文档,因为您只关心是否存在任何结果。

我不确定为什么您要在子集合中存储termsOfAgreement

[如果要检查是否存在termsOfAgreement为真的子文档,则可能要考虑向用户文档本身添加termsOfAgreement字段,这样就无需在整个文档之间执行查询子集合。

一旦用户接受了子集合中的任何条件,您就可以将此userDoc.termsOfAgreement设置为true,然后就不必再查询子集合(简化了读取代码并减少了读取操作的次数)。

© www.soinside.com 2019 - 2024. All rights reserved.