【问题标题】:'onCreate' firebase cloud function error“onCreate”firebase 云功能错误
【发布时间】:2018-11-17 02:40:24
【问题描述】:

我正在通过 firebase 云功能在 android 上推送通知。当我使用onWrite() 条件时,我的代码运行得非常好,我正在尝试实现此功能以进行评论,但在这种情况下,当有人编辑或喜欢评论时它会产生通知,所以我将其更改为 onCreate() 但现在我收到一个错误TypeError: Cannot read property 'val' of undefined

在这里..

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

我认为const comment = change.after.val(); 有问题,但我无法解决。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    你需要改变这个:

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

    进入这个:

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

    工作,因为onWrite 在实时数据库中创建、更新或删除数据时触发。因此,您可以检索数据 beforeafter 它已更改。

    onCreate() 在实时数据库中创建新数据时触发。因此只能检索新添加的数据,例如:

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

    更多信息在这里:

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

    在您的情况下,将其更改为:

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

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2021-10-16
      • 2017-10-09
      • 1970-01-01
      相关资源
      最近更新 更多