如何将变量插入Firebase快照?

时间:2019-04-14 23:21:15

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

我正在使用Firebase函数向用户发送通知。我可以像这样使用用户字符串插值:

      const original = change.after.val();
      const lover = context.auth.uid;

      const recipient_username = original.username;
      const topic = `${recipient_username}_notifications`;

但是现在我需要进行数据库调用以从user_id中获取用户名,并使用用户名从“原始”快照中获取loves的值,但这不起作用:

return db.ref('/users/' + lover).once('value', (snapshot) =>  {

          var username = snapshot.val().username;
          var love = original.loves.username // I need this to use the variable username, but it is just saying "username"

          console.log("lover username")
          console.log(username)
          console.log("loves")
          console.log(loves)

          const payload = {
            notification:{
              title: "You've got Love!",
              body: `${username} sent you Love! Refresh your inbox to recieve it, and why not send some back!`
            }
          };

如何将var love = original.loves.username更改为var love = original.loves.${username}

数据库如下:

   users/
         username: usernamehere
         love/
               otherusername: 10 // the amount of love they sent.

1 个答案:

答案 0 :(得分:2)

您在.val()上调用了original,将其转换为Javascript对象。

可以使用.loves帮助函数或使用字符串查找来完成Javascript对象中的遍历路径。尝试以下

var username = snapshot.val().username;
var love = original.loves[username];