gpt4 book ai didi

node.js - 创建文档时触发云函数时获取 "Object possibly undefined"

转载 作者:太空宇宙 更新时间:2023-11-03 23:14:32 25 4
gpt4 key购买 nike

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

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

最佳答案

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

  const newValue = snap.data();

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

console.log(newValue);

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

关于node.js - 创建文档时触发云函数时获取 "Object possibly undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57183349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com