Home > Mobile >  Correct way to use FieldValue.serverTimestamp() in Typescript
Correct way to use FieldValue.serverTimestamp() in Typescript

Time:12-29

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)
  }
})

CodePudding user response:

The reason serverTimestamp is undefined, is because you are using import yet that is an invalid way of using the import syntax and also you are not importing a module.

Use const instead of import

const FieldValue = firestore.FieldValue;

CodePudding user response:

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;
  }
})
  • Related