【问题标题】:Firestore cloud functions Comment Counter: How to fix "Object is possibly undefined"?Firestore 云功能评论计数器:如何修复“对象可能未定义”?
【发布时间】:2019-08-04 00:44:18
【问题描述】:

要求的行为:
我想在打字稿中创建一个云函数,每次将文档添加到帖子集合的 cmets 子集合时都会执行该函数。 执行应将父文档上的计数器加一。

当前状态
如果我用 console.log() 语句替换“get promise”,则每次创建文档时都会执行云函数。

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

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

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

我的云功能
如果你想复制代码

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 行是什么,错误消息告诉您存在问题的位置会更有帮助。

标签: javascript typescript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

错误告诉你错误在第 38 行。由于你没有说是哪一行,我猜测它在这一行:

    const data = snapshot.data()

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

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

或类似的东西。

【讨论】:

  • 谢谢,到目前为止有效。但后来我得到一个新的错误。它出现在.then(snapshot => { 行,说Argument of type '(snapshot: DocumentSnapshot) => Promise<WriteResult> | null' is not assignable to parameter of type '(value: DocumentSnapshot) => WriteResult | PromiseLike<WriteResult>'. Type 'Promise<WriteResult> | null' is not assignable to type 'WriteResult | PromiseLike<WriteResult>'. Type 'null' is not assignable to type 'WriteResult | PromiseLike<WriteResult>'.
  • 您还需要返回一个在所有异步工作完成后解决的承诺。 return admin.firestore()...
  • if(data) {...} else {return admin.firestore().doc(docPath).update({})} 是一个好的解决方案吗?因为它总是在 firebase 控制台中记录一条 info 语句。有更好的解决方案吗?
  • 每次成功的函数调用总是记录两个信息行。我认为您无法避免这种情况。
猜你喜欢
  • 2019-12-09
  • 1970-01-01
  • 2020-03-12
  • 2019-08-05
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多