Firestore云功能评论计数器:如何修复“对象可能未定义"? [英] Firestore cloud functions Comment Counter: How to fix "Object is possibly undefined"?

查看:81
本文介绍了Firestore云功能评论计数器:如何修复“对象可能未定义"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请求的行为:
我想在打字稿中创建一个云函数,每当将文档添加到帖子集合的注释子集合时,该函数就会执行. 执行应将父文档上的计数器增加一个.

Requested behaviour:
I would like to create a cloud function in typescript which gets executed every time a document gets added to a comments subcollection of a posts collection. The execution should increase a counter on the parent document by one.

当前状态
如果我用console.log()语句替换获取承诺",则每次创建文档时都会执行云功能.

Current State
The cloud function gets executed every time I create a document if I replace the "get promise" by a console.log() statement.

问题
它不执行更新部分.相反,它将引发错误: Object is possibly 'undefined'

issue
It does not execute the update part. Instead, it throws an error: Object is possibly 'undefined'

解决方法
我在不同的云函数中遇到了类似的问题,并使用了if语句来解决它.但是,我不明白如何在这里应用它.

solution approaches
I had a similar issue at a different cloud function and used an if statement to solve it. However, I do not understand how to apply it here.

如何解决此问题?我必须使用if语句吗?

How can I fix this issue? Do I have to use an if statement?

我的云功能
要复制的代码

My cloud function
code if you want to copy it

export const createSubCollTrigger = 
functions.firestore.document('posts/{postID}/comments/{commentID}').onCreate((snap, context) => {

    admin.firestore().doc('posts/{postID}').get()
    .then(snapshot => {
        const data = snapshot.data()
        return admin.firestore().doc('posts/{postID}').update({postCommentsTot: data.postCommentsTot + 1});  
    })

    .catch(error => {
        console.log(error)
        return
    })
})

**

推荐答案

该错误告诉您该错误位于第38行.由于您未说明是哪一行,因此我猜测它在这个:

The error is telling you that the error is on line 38. Since you didn't say which line that is, I'm going to guess that it's on this one:

    const data = snapshot.data()

根据 API文档 ,data()返回DocumentData or undefined,其中undefined表示未找到文档.在TypeScript中,这意味着您的代码需要表明它已准备好处理undefined,以便访问返回的对象上的属性.你不是在这里如您所建议,您需要使用条件来确定文档是否存在:

According to the API docs, data() returns DocumentData or undefined, where undefined indicates no document was found. In TypeScript, this means your code needs to show that it's prepared to handle undefined in order to access properties on the returned object. You're not doing that here. As you suggested, you need to use a conditional to determine if the document exists:

const data = snapshot.data()
if (data) {
    return admin.firestore().doc('posts/{postID}').update({postCommentsTot: data.postCommentsTot + 1});
}
else {
    return null
}

或类似的东西.

这篇关于Firestore云功能评论计数器:如何修复“对象可能未定义"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆