簡體   English   中英

Firestore雲功能評論計數器:如何修復“對象可能未定義”?

[英]Firestore cloud functions Comment Counter: How to fix “Object is possibly undefined”?

要求的行為:
我想在打字稿中創建一個雲函數,每當將文檔添加到帖子集合的注釋子集合時,該函數就會執行。 執行應將父文檔上的計數器增加一。

當前狀態
如果我用console.log()語句替換“獲取承諾”,則每次創建文檔時都會執行雲函數。

問題
它不執行更新部分。 相反,它引發錯誤: 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行上。由於您沒有說明是哪一行,因此我猜測它在這一行上:

    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
}

或類似的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM