Firestore Timestamp Invalid Data (Node / Javascript)

Apr 15, 2020
Unsupported field value: a custom object

firebase-admin is Node.js / Server SDK, while @firebase/testing is a Web / Client SDK. If you mix the API and Data Type (Timestamp) from these libraries, you will get

Unhandled error Error [FirebaseError]: Function DocumentReference.set() called with invalid data. Unsupported field value: a custom object (found in field created)

In the following example, we use @firebase/testing API with a firebase-functions Timestamp data type, thus causing the above exception.

const functions = require('firebase-functions');const projectId = 'PROJECT_NAME'// testing with firebase emulatorconst firebase = require('@firebase/testing')const db = firebase.initializeTestApp({ projectId: projectId }).firestore()const admin = require('firebase-admin')/*admin.initializeApp(functions.config().firebase)const db = admin.firestore()*/exports.requestInvite = functions.https.onCall(async (data, context) => {  const email = data.email  // use email as docId  const docId = Buffer.from(email).toString('base64')  const docRef = db.collection('request_invite').doc(docId)  await docRef.set({    // SHOULD use firebase.firestore.Timestamp.now() instead since the db(API) is from @firebase/testing    created: admin.firestore.Timestamp.now(),    email: email  })  return {    text: `Hello ${email}!`,    docId: docRef.id  }})

To solve this we would use matching API and Data Type

Use @firebase/testing

const projectId = 'PROJECT_NAME'// testing with firebase emulatorconst firebase = require('@firebase/testing')const db = firebase.initializeTestApp({ projectId: projectId }).firestore()const firestore = firebase.firestore...await docRef.set({  created: firebase.firestore.Timestamp.now(),  email: email})

or

Use firebase-admin

const admin = require('firebase-admin')admin.initializeApp(functions.config().firebase)const db = admin.firestore()...await docRef.set({  created: admin.firestore.Timestamp.now(),  email: email})

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.