在创建文档时触发Cloud Function时获取“对象可能未定义”

时间:2019-07-24 12:48:20

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

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

下面的代码仅在创建新文档时触发,而无法在该文档中获取用于通过电子邮件,电话和随机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:');
        });


    });

在这些代码行中,常量“ newValue”出现错误“对象可能未定义”。

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

1 个答案:

答案 0 :(得分:0)

我的第一个猜测是打字稿编译器不知道 <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div class="jumbotron text-center"> <h1>My First Bootstrap Page</h1> <p>Resize this responsive page to see the effect!</p> </div> <div class="container"> <div class="row"> <div class="col-sm-4"> <h3>Column 1</h3> <input id="image1" onclick="return openmodal(this);"/> </div> <div class="col-sm-4"> <h3>Column 2</h3> <input id="image2" onclick="return openmodal(this);"/> </div> <div class="col-sm-4"> <h3>Column 3</h3> <input id="image3" onclick="return openmodal(this);"/> </div> </div> </div> <!-- Modal --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <a class="hello" data-id="2" >2</p> <a class="hello" data-id="3" >3</p> <a class="hello" data-id="4" >4</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div>是否具有值,因此您需要检查一下:

snap.data()

如果确实是这种情况,则稍后可能会遇到相同的问题,因为无法确定 const newValue = snap.data(); if (newValue) { const email = newValue.email; const phone = newValue.phone; console.log(newValue); 具有newValueemail属性。如果您收到类似的消息,也必须为其添加类似的支票。