[英]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:我有以下实时数据库架构:
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当用户点击赞按钮时,一个新条目将添加到 myLikes->userId 列表
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.当新条目完成时,云 function 被触发在 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);
});
The function gets triggered ok but no entries are inserted into the realtime database. function 被触发正常,但没有条目插入实时数据库。 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.该语法不适用于 set 语句。 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除了@GrahamD 建议的语法更正之外,我还必须更改
exports.whoLikedMe = functions.database.ref('/myLikes/{userId}')
with和
exports.whoLikedMe = functions.database.ref('/myLikes/{userId}/{timestamp')
and now all is working fine.现在一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.