Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use FieldValue.serverTimestamp() in Typescript

Using Tyepscript, I'm trying to set the createdAt field in one of my Firebase functions with FieldValue.serverTimestamp() but I'm always getting the following error:

Cannot read properties of undefined (reading 'serverTimestamp'){"severity":"WARNING","message":"Function returned undefined, expected Promise or value"}

What datatype should I be using for this to work? In my code below I created a Category interface.

import * as functions from "firebase-functions";
import * as admin from 'firebase-admin';
import {firestore} from "firebase-admin";
import FieldValue = firestore.FieldValue;


interface Category {
  name: string;
  uid: string;
  createdAt: FieldValue;
}

export const createUser = functions.auth.user().onCreate((user) => {
  const db = admin.firestore()
  const ref = db.collection(`users/${user.uid}/category`).doc()

  try {
    const category: Category = {
      name: `test`,
      uid: user.uid,
      createdAt: FieldValue.serverTimestamp()
    }
    ref.set(category)
  }
  catch(e) {
    console.log((e as Error).message)
  }
})
like image 297
enchance Avatar asked Dec 19 '25 18:12

enchance


1 Answers

Firebase Admin SDK uses a modular syntax like client SDKs to some extent from v10. Try refactoring the code as shown below:

import * as functions from "firebase-functions";
import { initializeApp } from "firebase-admin/app";
import { FieldValue, getFirestore } from "firebase-admin/firestore";

initializeApp();

const db = getFirestore()
const serverTimestamp = FieldValue.serverTimestamp();

export const createUser = functions.auth.user().onCreate(async (user) => {
  const ref = db.collection(`users/${user.uid}/category`).doc()
  
  try {
    const category: Category = {
      name: `test`,
      uid: user.uid,
      createdAt: FieldValue.serverTimestamp()
    }
    await ref.set(category;
  } catch (e) {
    console.log((e as Error).message)
    return;
  }
})
like image 149
Dharmaraj Avatar answered Dec 21 '25 08:12

Dharmaraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!