I am currently utilizing firebase-admin
to manage a firestore database using Cloud Functions in TypeScript. I have encountered an issue where setting the type of my collection reference prevents me from using add
with FieldValue
s. The add
method now requires a literal object that matches the collection document structure, without any FieldValue
s. Can someone provide guidance on a recommended approach for using FieldValue
s with firebase-admin
in TypeScript? Any solution utilizing the core libraries with FieldValue
s will suffice.
Below is a basic example involving FieldValue.serverTimestamp
:
import { firestore, initializeApp } from 'firebase-admin'
import { firebaseConfig } from './secret'
import { https } from 'firebase-functions'
interface User {
id?: string
displayName: string
createdAt: firestore.Timestamp
}
const converter = {
toFirestore: (data: User) => data,
fromFirestore: (snapshot: firestore.QueryDocumentSnapshot<User>): User => {
const data = snapshot.data()
const doc = { id: snapshot.id, ...data }
return doc
}
}
initializeApp(firebaseConfig)
const db = firestore()
const usersCollectionRef = db.collection('users').withConverter(converter)
export const cloudFunction = https.onCall(async (props, context) => {
const newUserData = {
displayName: 'New User',
createdAt: firestore.FieldValue.serverTimestamp()
}
await usersCollectionRef.add(newUserData)
// Issue arising due to incompatible argument types when using FieldValue with Timestamp
})
Similarly, with FieldValue.arrayUnion
:
interface User {
id?: string
friendNames: string[]
}
const converter = {
toFirestore: (data: User) => data,
fromFirestore: (snapshot: firestore.QueryDocumentSnapshot<User>): User => {
const data = snapshot.data()
const doc = { id: snapshot.id, ...data }
return doc
}
}
initializeApp(firebaseConfig)
const db = firestore()
const usersCollectionRef = db.collection('users').withConverter(converter)
export const cloudFunction = https.onCall(async (props, context) => {
await usersCollectionRef.add({
friendNames: firestore.FieldValue.arrayUnion('BFF')
// Conundrum caused by missing properties of 'string[]' when using FieldValue with arrayUnion
})
})