【问题标题】:How to interpolate variable into firebase snapshot?如何将变量插入到 Firebase 快照中?
【发布时间】:2019-09-04 22:43:33
【问题描述】:

我正在使用 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.

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2021-06-16
      • 1970-01-01
      • 2017-03-05
      • 2020-05-11
      • 1970-01-01
      • 2018-01-23
      • 2017-09-10
      相关资源
      最近更新 更多