如何在NodeJS的Firestore中输入Firestore查询

kmbjn2e3  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(135)

我有下面的查询,它可以工作

const queryRef = firestore.collection('playlists').where('machines', 'array-contains', id)
const snapshot = await queryRef.get()

...

const playlist = document.data() as Playlist // I want to avoid this cast using `as`

然而,它将数据转换为我想要的类型,我想我可以使用DocumentReference或其他东西来转换我的查询,这可能吗?

t3psigkw

t3psigkw1#

是的,你可以在不使用as关键字的情况下将firestore文档转换为你想要的类型,为此你需要创建**Custom Objects Convertor**。
我在这里使用Firebase V9:

import { DocumentData, FirestoreDataConverter, QueryDocumentSnapshot, QuerySnapshot, Timestamp, collection, getDocs, query, where } from "firebase/firestore";
import { db } from "./config/firebase.js";

interface Playlist {
    name: string;
    count: number;
    isActive: boolean;
    date: Timestamp
}

const playListConverter: FirestoreDataConverter<Playlist> = {
    toFirestore(Playlist: Playlist): DocumentData {
        return Playlist;
    },
    fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>): Playlist {
        const data = snapshot.data();
        return {
            name: data.name,
            count: data.count,
            isActive: data.isActive,
            date: data.date,
        };
    },
};

let playlists : Playlist[] = []; // empty initialization

const ref = collection(db, "mocks");
const q = query(ref, where("isActive", "==", true));
const snaps: QuerySnapshot<Playlist> = await getDocs(q.withConverter(playListConverter));

snaps.forEach((doc) => {
    playlists.push(doc.data());
});

for(let playlist of playlists){
    console.log(playlist);
}

如果这感觉多余,你仍然可以使用as关键字来摆脱,如下所示:

interface Playlist {
    name: string;
    count: number;
    isActive: boolean;
    date: Timestamp
}

let playlists : Playlist[] = []

const ref = collection(db, "mocks");
const q = query(ref, where("isActive", "==", true));
const snaps = await getDocs(q);
snaps.forEach((doc) => {
    playlists.push(doc.data() as Playlist); // ⇐ still viable
});
for(let playlist of playlists){
    console.log(playlist);
}

参考:自定义对象

相关问题