从 Firestore 中获取 <T> 的数据

问题描述 投票:0回答:1

我正在使用 Firestore 的 Node 版本(我已经习惯了 Angular 版本)并且在语法上遇到了一些问题。

我有一个 firebase 表,它存储一组统一的对象,所有对象都符合名为“ArchiveRecord”的打字稿接口,存储在一个名为

BKArchive
.

的集合中

我可以通过 id 作为通用

DocumentData
取回这些记录,但我想将它们作为
ArchiveRecords
取回。

好像是这样的:

let fs = getFirestore(app)
let myDoc = await getDoc<ArchiveRecord>(fs, 'BKArchive', docId)

它似乎应该工作,但我在

fs
参数到
getDoc()
(fs 应该是一个 Firestore 实例)上遇到一个奇怪的编译错误。错误信息是
Argument of type 'Firestore' is not assignable to parameter of type 'CollectionReference<ArchiveRecord>'.

根据文档,该消息对我来说没有任何意义,它应该是一个 Firestore 实例。

firebase google-cloud-firestore
1个回答
1
投票

您收到的错误意味着

getDoc()
期待
DocumentReference
QueryDocumentSnapshot
看看这个docs

您可以接收从

getDoc()
返回的数据作为
ArchiveRecord
的类型,如下所示:

import { initializeApp } from "firebase/app";
import { getFirestore, doc, getDoc } from 'firebase/firestore';
import { ArchiveRecord } from './ArchiveRecord'; // import for ArchiveRecord
const firebaseConfig = {
   // …
};
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app); //firestore initialized 
const docRef = doc(firestore, 'BKArchive', docId);
const snapshot = await getDoc(docRef);
// Bellow is your record with all type safety assuming all
// document data is of the same type.
const myRecord = snapshot.data() as ArchiveRecord;

基本上,我们使用

ArchiveRecord
关键字将从 Firestore 接收的数据投射到您的
as
界面。 您可能认为这也应该可行:
const snapshot = await getDoc<ArchiveRecord>(docRef);
但它不会,因为
snapshot
不会被转换为
ArchiveRecord
snapshot.data()
可以被转换为
ArchiveRecord
;

© www.soinside.com 2019 - 2024. All rights reserved.