我有一个看起来像下面的类。
export class Business {
name: string;
docRef: DocumentReference;
constructor(name: string, docRef: DocumentReference) {
this.name = name;
this.docRef = docRef;
}
}
我想要的是能够在Firestore中轻松地操作这个对象,以存储... DocumentReference
获取数据时。例如目前我有以下内容。
this.firestore.collection<Business>('businesses').doc<Business>(id).valueChanges();
...但我知道我需要用... snapshotChanges
来获取元数据(即DocumentReference)。
我怎样才能轻松地将 DocumentReference
进入我 Business
对象时,我检索它?谢谢大家的帮助。
答案比我预想的要简单,所以我决定回来这里把答案贴出来,看看对大家有没有帮助。
鉴于这个例子 Business
加入以下方法 Business
:
static fromFirestore(doc: DocumentSnapshot<Business>): Business {
return ({
name: doc.data().name,
docRef: doc.ref,
});
}
然后在读取它时调用下面的函数。
this.firestore.collection<Business>('businesses').doc<Business>(id).snapshotChanges().subscribe((value) => {
this.business = Business.fromFirestore(value.payload);
});
或者,如果你想返回一个可观察的字符串,可以这样做。
return this.firestore.collection<Business>('businesses').doc<Business>(id).snapshotChanges().pipe(
map(value => Business.fromFirestore(value.payload))
);
希望这能帮到你