8

I am trying to add a user object to firestore when a user registers through google auth. here is my code:

export const accountCreate = functions.auth.user().onCreate(user => {
    console.log(user.data);
    admin.firestore().collection('users').doc(user.data.uid).set(user.data).then(writeResult => {
        console.log('User Created result:', writeResult);
        return;
    }).catch(err => {
        console.log(err);
        return;
    });
});

No luck, I just keep getting the error:

Error: Cannot encode type ([object Object]) to a Firestore Value at Function.encodeValue (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:773:11)

I am not sure why this isn't working. Any Ideas? Thanks

2 Answers 2

9

user.data isn't a valid Cloud Firestore document, so Firestore is rejecting the write. Instead, you should set the specific fields you care about, e.g.:

export const accountCreate = functions.auth.user().onCreate(user => {
    console.log(user.data);
    userDoc = {'email' = user.data.email, 
               'displayName' = user.data.displayName}
    admin.firestore().collection('users').doc(user.data.uid)
    .set(userDoc).then(writeResult => {
        console.log('User Created result:', writeResult);
        return;
    }).catch(err => {
       console.log(err);
       return;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

4

Following from Dans answer, it's possible to just serialize the UserRecord and place everything into the document without having to think about what you:

A complete working example:

import * as functions from 'firebase-functions';

const admin = require('firebase-admin');

admin.initializeApp({
  databaseURL: 'https://challenges-f9f6b.firebaseio.com'
});

export const addUser = functions.auth.user().onCreate((user) => {
  return admin
    .firestore()
    .collection('users')
    .doc(user.uid)
    .set(JSON.parse(JSON.stringify(user)));
});

1 Comment

import * as functions from 'firebase-functions' doesn't work for V2 functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.