Javascript FireStore查询单个文档
背景:我试图用一个值而不是ID从集合中检索一个文档。我基本上是在尝试建立一个登录系统 我尝试了这个解决方案: 使用flat map to和limit(1)执行此操作,但它似乎没有提供任何信息,这就是我的代码现在的样子:Javascript FireStore查询单个文档,javascript,angular,angularfire2,google-cloud-firestore,Javascript,Angular,Angularfire2,Google Cloud Firestore,背景:我试图用一个值而不是ID从集合中检索一个文档。我基本上是在尝试建立一个登录系统 我尝试了这个解决方案: 使用flat map to和limit(1)执行此操作,但它似乎没有提供任何信息,这就是我的代码现在的样子: this.user = this.afs.collection('users/', ref => ref.where('username', '==', this.username).limit(1)).valueChanges().flatMap(result
this.user = this.afs.collection('users/', ref => ref.where('username',
'==', this.username).limit(1)).valueChanges().flatMap(result => result);
console.log(this.user.username);
输出是未定义的,但是如果我只打印用户,我确实得到了可观察的,您应该将此设置为
。用户
到可观察的引用,然后像这样订阅它:
this.user = this.afs.collection('users', (ref) => ref.where('username', '==', this.username).limit(1)).valueChanges();
// I removed the slash after 'users' as it isn't necessary
this.user = this.afs.collection('users',
(ref) => {
return ref.where('username', '==', this.username).limit(1)
})
.snapshotChanges()
.map((users) => {
return users.length
});
然后像这样订阅可观察到的内容:
this.user.subscribe((user) => {
console.log(user);
});
这只会给你一个结果。控制台记录可观察对象不会显示数据,而是记录可观察对象
请注意,您应该拥有与该用户名相关的userId,并取而代之地获取文档,因为它比获取与字段匹配的集合并将其限制为1更安全、更明确。如果这是身份验证问题,您应该使用Firebase Auth,并使用任何形式的身份验证作为用户名,Firebase Auth将处理没有重复登录的问题。如果希望使用用户名而不是电子邮件,您可以请求,但您的方法应该只返回请求的长度,如下所示:
this.user = this.afs.collection('users', (ref) => ref.where('username', '==', this.username).limit(1)).valueChanges();
// I removed the slash after 'users' as it isn't necessary
this.user = this.afs.collection('users',
(ref) => {
return ref.where('username', '==', this.username).limit(1)
})
.snapshotChanges()
.map((users) => {
return users.length
});
这样,您就不会在请求中返回用户对象,而是返回一个数字,如果该数字大于零,则表示用户已经拥有该用户名
由于您使用的是
valueChanges()
而不是snapshotChanges()
,因此在DOM上显示数据之前似乎不需要操作数据,因此您不需要订阅数据,而是使用标记中的异步管道订阅可观察数据。这是我前几天问的一个问题,它解释了您的问题以及在标记中使用异步管道:您如何在html中显示它?