2
votes

I want to create a function that will add data to firestore on authentication trigger.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.addUserData = functions.auth.user().onCreate(event => {
    const user = event.data;
    const userUid = user.uid;
    return db.collection('peoples').doc(userUid).set({
        name:user.displayName,
        uid:user.uid
    });
});

But it gives the error

Error: Cannot encode type ([object Undefined]) to a Firestore Value at Function.encodeValue (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:775:11) at Function.encodeFields (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:646:36) at Function.fromObject (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:202:55) at WriteBatch.set (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/write-batch.js:272:39) at DocumentReference.set (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/reference.js:425:8) at exports.addUserData.functions.auth.user.onCreate.event (/user_code/index.js:9:46) at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27) at next (native) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)

askfirebase

1

1 Answers

3
votes

The error message says that one of the values you're passing in is undefined. Given you code, the uid is unlikely to ever be undefined so that leaves the display name as the likely cause.

A user profile is not required to have a display name, so you code should handle the case where it doesn't.

const user = event.data;
const userUid = user.uid;
const userName = user.displayName ? '';
return db.collection('peoples').doc(userUid).set({
    name: userName,
    uid: userUid
});