创建文档时触发云函数时出现“对象可能未定义”

And*_*che 3 node.js firebase typescript google-cloud-functions google-cloud-firestore

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

下面的代码仅在创建新文档时触发,但无法获取该文档中的值来创建具有电子邮件、电话和随机 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:');
        });


    });
Run Code Online (Sandbox Code Playgroud)

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

const email = newValue.email;
const phone = newValue.phone;
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 5

我的第一个猜测是打字稿编译器无法知道是否snap.data()有值,因此您需要检查:

  const newValue = snap.data();

  if (newValue) {
    const email = newValue.email;
    const phone = newValue.phone;

    console.log(newValue);
Run Code Online (Sandbox Code Playgroud)

如果确实如此,那么以后可能会遇到同样的问题,因为它无法确定newValuehasemailphone属性。如果您收到类似的消息,您也必须为它们添加类似的检查。