如何在Firestore中访问特定文档的子集合?
我已经创建了用户,并将其存储在users
集合中。现在,每个用户登录时,我都可以通过以下方式获取各自的数据displayName
和email
:
this.user = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
} else {
return of(null)
}
})
)
结构看起来或多或少是这样的:
users:{
userID1: { displayName: 'name1', email: 'email1@mail.com'
favorites: {
favoriteID1: { title: 'title1', description: 'description1' },
favoriteID2: { title: 'title2', description: 'description2' }
}
},
userID2: { displayName: 'name2', email: 'email2@mail.com' },
userID3: { displayName: 'name3', email: 'email3@mail.com' },
}
如何仅为已登录的用户访问favorites
子集合?
答案 0 :(得分:0)
使用Firestore,您可以访问文档参考中的集合,请参见https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#collection
因此它类似于db.collection("users").doc("id").collection("favorites").get()
希望有帮助!
答案 1 :(得分:0)
来自https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md
您可以在AngularFirestoreDocument上执行.collection<Foo>('foos')
。
方法A:
this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
let userDoc = this.afs.doc<User>(`users/${user.uid}`);
this.user$ = userDoc.valueChanges();
this.userFavs$ = userDoc.collection<Favorite>('favorites').valueChanges();
} else {
this.user$ = of(null);
this.userFavs$ = of(null);
}
})
);
方法B:
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
})
);
this.userFavs$ = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
let userDoc = this.afs.doc<User>(`users/${user.uid}`);
return userDoc.collection<Favorite>('favorites').valueChanges();
} else {
return of(null);
}
})
);