简体   繁体   中英

How to Write Data Into Firebase Realtime Database with Cloud Functions when new Data is added to a Specific Child

I have the following realtime database schema:

schema

I'm working on a social app where a user can like another user. When the user clicks on the like button, a new entry will be added to myLikes->userId list

MyLike myLike = new MyLike(userId, System.currentTimeMillis();
         FirebaseDatabase.getInstance().getReference().child("myLikes").child(userId).child(System.currentTimeMillis()).setValue(myLike);

When the new entry is completed, the cloud function gets triggered to write a new entry in whoLikedMe>userId list for the other User who has been liked.

exports.whoLikedMe = functions.database.ref('/myLikes/{userId}')
    .onWrite((change, context) => {
      // Only edit data when it is first created.
      if (change.before.exists()) {
        return null;
      }
      // Exit when the data is deleted.
      if (!change.after.exists()) {
        return null;
      }
      // Grab the current value of what was written to the Realtime Database.
      const data2 = change.after.val();
      const likedDate = data2.date;
      const myUserId = data2.I_Liked_UserId;
      var likedMe = {
            date: likedDate,
            Who_Liked_Me_UserId: myUserId,
        }

      //get the current date in millis  
      var hrTime = process.hrtime();
      const dateMillis = hrTime[0];
      return admin.database().ref('/WholikedMe/'+myUserId+'/'+hrTime[0]).set(likedMe);
    });

The function gets triggered ok but no entries are inserted into the realtime database. What I'm doing wrong?

EDIT:

When I changed:

exports.whoLikedMe = functions.database.ref('/myLikes/{userId}')

with

exports.whoLikedMe = functions.database.ref('/myLikes/{userId}/915170400000')

(which adds the hardcoded timestamp to the path) all works fine. The problem is that the timestamp is constantly changing. any idea how to accomplish this with the timestamp?

You're using wildcard syntax (curly braces) in the following line:

return change.after.ref('/WholikedMe/{myUserId}/{hrTime[0]}').set(likeMe)

That syntax does not apply to a set statement. You need to use:

return change.after.ref('/WholikedMe/' + myUserId + '/' + hrTime[0]).set(likeMe)

... I think, doing this on my phone so can't double check. :-)

I figure d out. In addition to the syntax correction suggested by @GrahamD I had to change

exports.whoLikedMe = functions.database.ref('/myLikes/{userId}')

with

exports.whoLikedMe = functions.database.ref('/myLikes/{userId}/{timestamp')

and now all is working fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM