【问题标题】:Firebase cloud function with realtime database triggers: how to update the source node?具有实时数据库触发器的 Firebase 云功能:如何更新源节点?
【发布时间】:2020-05-18 10:43:45
【问题描述】:

我正在尝试编写一个执行以下操作的云函数:

  1. 在“posts/{postid}/cmets/{cmetsid}/”节点中收听新创建。 (这是通过前端代码的数据库推送完成的)。此节点将在“uid”子节点下拥有评论者的 uid。
  2. 使用子节点中的 uid,在“users/uid”节点中查找评论者的用户名、昵称和头像并记录。
  3. 使用用户名、昵称和头像的相关子节点更新“posts/{postid}/cmets/{cmetsid}/”节点。

下面的代码可以正常工作,直到尝试完成这项工作的最后一部分。 3. 错误信息是'Function returned undefined, expected Promise or value'。

我认为这是 Firebase 特有的语法问题。有人可以指出我用于完成任务的正确语法吗?

非常感谢!

 exports.commentsupdate = functions.database.ref('posts/{postid}/comments/{commentsid}/')
  .onCreate((snapshot,context) => {
     const uid=snapshot.val()['uid'];
     let username="";
     let nickname="";
     let profile_picture="";
     const ref1=database.ref('users/'+uid);
     ref1.once('value',function(ssnapshot){
        username=ssnapshot.val()['username'];
        nickname=ssnapshot.val()['nickname'];
        profile_picture=ssnapshot.val()['profile_picture'];
     }).then(()=>{
        return snapshot.ref.update({
           username:username,
           nickname:nickname,
           profile_picture:profile_picture
       })
    })
});

【问题讨论】:

  • 我相信这是因为快照参数没有返回承诺。尝试使用 admin.database().ref('your ref here').update

标签: node.js firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

需要返回Promises链中的第一个Promise,即once()方法返回的Promise,如下:

exports.commentsupdate = functions.database.ref('posts/{postid}/comments/{commentsid}/')
    .onCreate((snapshot, context) => {

        const uid = snapshot.val()['uid'];
        let username = "";
        let nickname = "";
        let profile_picture = "";

        const ref1 = database.ref('users/' + uid);

        return ref1.once('value')   // <--- Note the return here
            .then(snapshot => {
                username = snapshot.val()['username'];
                nickname = snapshot.val()['nickname'];
                profile_picture = snapshot.val()['profile_picture'];

                return snapshot.ref.update({
                    username: username,
                    nickname: nickname,
                    profile_picture: profile_picture
                })

            })

    });

我建议您观看 Firebase 视频系列中有关“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2018-02-02
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    相关资源
    最近更新 更多