当新数据添加到特定子项时,如何使用云函数将数据写入Firebase实时数据库



我有以下实时数据库模式:

模式

我正在开发一个社交应用程序,一个用户可以喜欢另一个用户。当用户点击点赞按钮时,将向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')

(它将硬编码的时间戳添加到路径中(一切都很好。问题是时间戳在不断变化。知道如何使用时间戳来实现这一点吗?

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

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

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

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

我想,在我的手机上做这件事,所以不能重复检查。:-(

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

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

带有

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

现在一切都很好。

最新更新