我正在使用
firebase-admin
来控制使用 Cloud Functions 和 TypeScript 的 firestore 数据库。当我将类型添加到我的集合引用时,我不能再使用 add
s FieldValue
。 add
的参数类型需要一个与集合文档匹配的文字对象,没有任何 FieldValue
s。我如何在 TypeScript 中使用 FieldValue
s 和 firebase-admin
?
这是一个最小的例子:
import { firestore, initializeApp } from 'firebase-admin'
import { firebaseConfig } from './secret'
import { https } from 'firebase-functions'
interface User {
displayName: string
createdAt: {
seconds: number
nanoseconds: number
}
}
function dataFromFirestore (snapshot: firestore.QueryDocumentSnapshot<User>): User {
const data = snapshot.data()
const doc = { id: snapshot.id, ...data }
return doc
}
function dataToFirestore (data: Partial<User>): Partial<User> {
return data
}
const converter = {
toFirestore: dataToFirestore,
fromFirestore: dataFromFirestore
}
initializeApp(firebaseConfig)
const db = firestore()
const usersCollectionRef = db.collection('users').withConverter(converter)
export const cloudFunction = https.onCall(async (props, context) => {
if (context.app == null) {
throw new https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.'
)
}
const newUserData = {
displayName: 'New User',
createdAt: firestore.FieldValue.serverTimestamp()
}
await usersCollectionRef.add(newUserData)
// Argument of type '{ displayName: string; createdAt: firestore.FieldValue; }' is not assignable to parameter of type 'User'.
// Types of property 'createdAt' are incompatible.
// Type 'FieldValue' is missing the following properties from type '{ seconds: number; nanoseconds: number; }': seconds, nanoseconds
})