首页 > 解决方案 > TypeScript:Firestore withConverter 和 refrences

问题描述

我对 Firestore/Firebase 相当陌生。我有这个专辑类,可以保存对父专辑的引用

export class Album {
    constructor(public id: string,
                public title: string,
                public parent: Album | null,
    ) {
    }
}

export class AlbumConverter implements FirestoreDataConverter<ImageData> {
    toFirestore(album: Album): firebase.firestore.DocumentData {
        return {
            id: album.id,
            title: album.title,
            parent: album.parent ?.....

我的问题是,我应该如何实现toFirestoreand fromFirestoreDataConverter处理引用时使用的正确方法是什么?

谢谢!

标签: typescriptfirebasegoogle-cloud-firestore

解决方案


您必须将DocumentReference作为parent.

要获得参考,您可以做例如:

   function getRef = (id: string): Promise<any> {
        return new Promise<Track>(async (resolve, reject) => {
            const query = this.db.collection(this.collectionPath).where('id', '==', id); 
            const querySnapshot = await query.get();

            if (querySnapshot.empty) {
                return reject("not found")
            }

            return resolve(querySnapshot.docs[0].ref);
        });
    }

接着 :

const parentRef = await getRef(parentId);

const albumConverter = {
    toFirestore: (album: Album) => {
        return {
            id: album.id,
            title: album.title,
            parent: parentRef
        }
    }
}

推荐阅读