具有实时数据库触发器的Firebase云功能:如何更新源节点?

时间:2020-02-02 12:57:07

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

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

  1. 在“ posts / {postid} / comments / {commentsid} /”节点中收听新创建的内容。 (这是通过从前端代码推送数据库来完成的)。该节点将在“ uid”子节点下具有评论者的uid。
  2. 使用子节点中的uid,在“用户/ uid”节点中查找评论者的用户名,昵称和个人资料图片,并将其记录下来。
  3. 使用相关子节点的用户名,昵称和个人资料图片更新“ posts / {postid} / comments / {commentsid} /”节点。

下面的代码可以正常工作,直到尝试执行此工作的最后一部分为止。 3.错误消息是“函数返回了未定义的,预期的承诺或价值”。

我认为这是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
       })
    })
});

1 个答案:

答案 0 :(得分:2)

您需要返回 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承诺”的3个视频:https://firebase.google.com/docs/functions/video-series/