云功能auth onCreate触发器将用户添加到firestore

时间:2018-01-25 21:38:54

标签: typescript firebase firebase-authentication google-cloud-functions google-cloud-firestore

当用户通过google auth注册时,我正在尝试将用户对象添加到firestore。这是我的代码:

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

没有运气,我只是不断收到错误:

错误:无法将类型([对象对象])编码为Firestore值     在Function.encodeValue(/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/document.js:773:11)

我不确定为什么这不起作用。有任何想法吗? 感谢

2 个答案:

答案 0 :(得分:2)

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Get the BackgroundWorker that raised this event. BackgroundWorker worker = sender as BackgroundWorker; e.Result =client.getData(); } 不是有效的Cloud Firestore文档,因此Firestore拒绝写入。相反,您应该设置您关心的特定字段,例如:

user.data

答案 1 :(得分:0)

根据Dans的回答,可以序列化UserRecord并将所有内容放入文档中,而无需考虑您的情况:

完整的工作示例:

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