J.Ko
J.Ko

Reputation: 8711

Firebase cloud function with realtime database triggers: how to update the source node?

I am trying to write a cloud function that does the following:

  1. Listen to a new creation in 'posts/{postid}/comments/{commentsid}/' node. (This is done from database push from the frontend code). This node will have the commenter's uid under 'uid' child node.
  2. Using the uid in the child node, Look for the commenter's username, nickname, and profile picture in the 'users/uid' node and log them.
  3. Update the 'posts/{postid}/comments/{commentsid}/' node with the relevant child nodes for username, nickname, and profile picture.

The code below works fine until the last part that try to do the job no. 3. The error message is 'Function returned undefined, expected Promise or value'.

I think this is a syntax problem specific to Firebase. Could someone point me to the right syntax to use to do the task?

Thanks a lot!

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

Upvotes: 0

Views: 427

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

You need to return the first Promise in the Promises chain, i.e. the Promise returned by the once() method, as follows:

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

            })

    });

I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/

Upvotes: 2

Related Questions