简体   繁体   中英

'onCreate' firebase cloud function error

I am working on Push notifications on android via firebase cloud functions. My code is working absolutely nice when I use onWrite() condition, I am trying to implement this function for commenting, but in this case when when someone edit or like comment it produces a notification, so I changed it to onCreate() but now I am getting an error TypeError: Cannot read property 'val' of undefined .

Here it is..

exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onCreate((change, context) => {

    const commentId = context.params.commentId;
    const postId = context.params.postId;
    const comment = change.after.val();
    const posType = "Post";


    const getPostTask = admin.database().ref(`/posts/${postId}`).once('value');

    return getPostTask.then(post => {
        // some code
    })
});

I think there is a problem in const comment = change.after.val(); but I am unable to figure it out.

You need to change this:

exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onCreate((change, context) => {

into this:

exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onWrite((change, context) => {

to work, since onWrite triggers when data is created, updated, or deleted in the Realtime Database. Therefore you are able to retrieve the data before and after it changed.

onCreate() triggers when new data is created in the Realtime Database. Therefore you can only retrieve the data that was newly added, example:

exports.dbCreate = functions.database.ref('/path').onCreate((snap, context) => {
 const createdData = snap.val(); // data that was created
});

more info here:

https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

In your case, change it to this:

exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onCreate((snap, context) => {

const commentId = context.params.commentId;
const postId = context.params.postId;
const comment = snap.val();
const posType = "Post";

});

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