【问题标题】:Getting "Object possibly undefined" when triggering Cloud Function on document creation [duplicate]在创建文档时触发云功能时获取“对象可能未定义”[重复]
【发布时间】:2019-12-02 15:11:28
【问题描述】:

每当在集合“用户”中添加新文档时,我都会尝试创建一个新的经过身份验证的用户。用户详细信息应在新文档中的“电子邮件”和“电话”字段中提供。

以下代码仅在创建新文档时触发,但无法获取该文档中的值以创建具有电子邮件、电话和随机 userId 的经过身份验证的用户。

import * as functions from 'firebase-functions';

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

admin.initializeApp();

exports.updateUser = functions.firestore

    .document('users/{user}').onCreate((snap, context) => {
      // ... Your code here

      const newValue = snap.data();

      const email = newValue.email;
      const phone = newValue.phone;

      console.log(newValue);

      console.log("new user added");

      admin.auth().createUser({
        uid: 'some-uid',
        email: email,
        phoneNumber: phone
      })
        .then(function() {
          // See the UserRecord reference doc for the contents of userRecord.
          console.log('Successfully created new user:');
        })
        .catch(function() {
          console.log('Error creating new user:');
        });


    });

我在这些代码行中收到错误“对象可能未定义”,因为 const “newValue”。

const email = newValue.email;
const phone = newValue.phone;

【问题讨论】:

    标签: node.js typescript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    我的第一个猜测是 typescript 编译器不知道 snap.data() 是否有值,所以你需要检查一下:

      const newValue = snap.data();
    
      if (newValue) {
        const email = newValue.email;
        const phone = newValue.phone;
    
        console.log(newValue);
    

    如果情况确实如此,那么以后可能会遇到同样的问题,因为它不能确定newValue 是否具有emailphone 属性。如果您收到类似的消息,您也必须为它们添加类似的检查。

    【讨论】:

    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多