【问题标题】:How to Write Data Into Firebase Realtime Database with Cloud Functions when new Data is added to a Specific Child将新数据添加到特定子项时如何使用 Cloud Functions 将数据写入 Firebase 实时数据库
【发布时间】:2020-11-18 06:49:52
【问题描述】:

我有以下实时数据库架构:

schema

我正在开发一个用户可以喜欢另一个用户的社交应用。当用户点击like按钮时,会在myLikes->userId列表中添加一个新条目

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

当新条目完成后,会触发云函数在 whoLikedMe>userId 列表中为其他已被赞的用户写入新条目。

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

函数触发正常,但没有条目插入实时数据库。我做错了什么?

编辑:

当我改变时:

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

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

(将硬编码的时间戳添加到路径)一切正常。问题是时间戳是不断变化的。知道如何使用时间戳来完成此操作吗?

【问题讨论】:

    标签: android firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    您在以下行中使用了通配符语法(大括号):

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

    该语法不适用于 set 语句。你需要使用:

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

    ...我想,在我的手机上执行此操作,因此无法仔细检查。 :-)

    【讨论】:

    • 你是对的。我已经使用您建议的语法更正编辑了代码,但现在我在日志中有一个不同的错误:错误:Reference.set 失败:第一个参数在属性“WholikedMe.undefined.90.date”中包含未定义。看起来属性 likeDate 和 myUserId 没有填充。此外,当我将硬编码值放入这些属性中时,一切正常。
    【解决方案2】:

    我想通了。除了@GrahamD 建议的语法更正之外,我还必须更改

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

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

    现在一切正常。

    【讨论】:

    • 所以请将我的答案标记为已接受,因为它解决了问题提出的最初问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-20
    • 2019-10-03
    • 2017-11-12
    • 2021-10-04
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多