【问题标题】:Firebase Cloud Functions. Cannot read property parent of undefined (.ref)Firebase 云功能。无法读取未定义 (.ref) 的属性父级
【发布时间】:2019-09-26 21:50:23
【问题描述】:

我正在尝试将以下功能部署到 firebase。该函数部署良好,但当函数触发时出现错误:cannot read property 'parent' of undefined。错误发生在我引用父级的第一行。我在快照和快照.ref上使用了console.log,虽然快照存在,但snapshot.ref是未定义的。

我在其他云功能中使用了 snapshot.ref.parent,它工作正常。此功能有两个主要区别: (a) 它是一个 onUpdate(我之前一直在使用 onCreate 和 onDelete) (b) 它是一个异步函数。

exports.likeRating = functions.database.ref('Ocean/{waveId}/Likes').onUpdate(async (snapshot) =>{
    let likes; let dislikes; let comments; let echoes;

    await snapshot.ref.parent.child('Dislikes').once('value').then(response=>{dislikes = response.val(); return null});
    await snapshot.ref.parent.child('Likes').once('value').then(response=>{likes = response.val(); return null});
    await snapshot.ref.parent.child('Comments').child('CommentsCount').once('value').then(response=>{comments = response.val(); return null});
    await snapshot.ref.parent.child('Echoes').once('value').then(response=>{echoes = response.val(); return null});

    snapshot.ref.parent.child('Rating').set(dislikes+likes+comments+echoes);
    return null;

}

关于我为什么会收到此错误的任何想法?感谢所有帮助。

【问题讨论】:

    标签: javascript node.js firebase


    【解决方案1】:

    该函数的运行速度将比它需要的慢得多,因为您正在等待一系列请求,您应该等待 Promise.all([<Promises>]) 代替,return null 也是多余的。

    我也不确定你为什么每次都加起来而不是增加 Rating 值,但也许我没有像你一样考虑。

    如果你查看docs,回调的签名是function(non-null functions.Change containing non-null functions.firestore.DocumentSnapshot, optional non-null functions.EventContext)

    所以第一个参数是change,其中包含beforeafter,它们的类型为DocumentSnapshot,这是您应该使用的属性,例如change.after.ref.

    【讨论】:

    • 感谢您的帮助多米尼克。我重写了我的代码并且它有效。我选择添加而不是增量的原因是因为我是一个完全的菜鸟 XD。在某种相关的注释上。在我的代码的不同部分中,我嵌套了 Promise (.then),我收到了关于这样做的警告 - 有没有更好的方法,即我应该使用 async await 还是有另一个像 Promise.all 这样的函数我不知道?
    猜你喜欢
    • 2018-12-05
    • 2020-05-18
    • 2019-03-18
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2015-03-01
    • 2018-09-29
    相关资源
    最近更新 更多