[英]Angular firestore query to firestore document
我有以下查詢
selectedUser$: AngularFirestoreDocument<any>;
this.selectedUser$ = this.userCollection.ref.where('uid', '==', key)
投擲錯誤
類型“查詢”不可分配給類型“AngularFirestoreDocument”。 “查詢”類型中缺少屬性“參考”。
我試過了
this.selectedUser$ = this.userCollection.ref.where('uid', '==', key).get()
沒有成功
基本上,我希望查詢返回 firestore 文檔
您得到的錯誤是因為您正在混合使用 firebase 本機 api 和 angularfire。
selectedUser$: AngularFirestoreDocument<any>;
在.ref
上調用AngularFirestoreCollection
會將其轉換為firebase.firestore.CollectionReference
類型
話雖如此,有兩種可能性可以解決您的問題:
使用angularfire
:
我假設您的 userCollection 看起來像這樣: this.afs.collection<User>
。 由於您正在查詢集合,因此無法確保您的查詢謂詞uid == key
在 firebase 中是唯一的。 因此,您查詢集合並limit()
結果。 這將返回一個包含一個文檔的數組。 flatMap()
將返回一個用戶。
this.afs.collection<User>('users', ref => ref.where('uid', '==', key).limit(1))
.valueChanges()
.pipe(
flatMap(users=> users)
);
使用firebase
原生 api:
const query = this.usersCollection.ref.where('uid', '==', key);
query.get().then(querySnapshot => {
if (querySnapshot.empty) {
console.log('no data found');
} else if (querySnapshot.size > 1) {
console.log('no unique data');
} else {
querySnapshot.forEach(documentSnapshot => {
this.selectedUser$ = this.afs.doc(documentSnapshot.ref);
// this.afs.doc(documentSnapshot.ref).valueChanges().subscribe(console.log);
});
}
});
這樣,如果需要,鏈接多個.where
子句會更容易一些
這適用於我的最新版本:2021-7 月
this.store
.collection("Products",ref=>ref.where("stock","==",10))
.get()
.subscribe(data=>data.forEach(el=>console.log(el.data())));
PS:我正在使用 get() 並且沒有事件偵聽器。
this.afs.collection<User>('users', ref => ref.where('uid', '==', key).limit(1))
);
如果您添加有關 Firestore 集合結構和 typescript 文件的更多詳細信息,將會更容易為您提供幫助。
但是,要查詢集合,我執行以下操作:
在構造函數中定義一個私有的 AngularFirestore。
constructor( private afStore: AngularFirestore, ) { }
定義查詢並將結果傳遞給 AngularFirestoreDocument。
this.selectedUser$ = this.afStore .collection('TheNameOfYourCollection').doc<any>(key);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.