简体   繁体   中英

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

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.

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

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

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.

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 }) }) 

**

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()

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
}

Or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM