【发布时间】:2020-11-06 18:38:44
【问题描述】:
如果节点不存在,我想向数据库添加一个新节点。我不想向客户端返回任何东西,我只想用新值更新数据库。在客户端上,我有一个监听器,它观察credit_counts 属性,一旦发生更新,它就会在那里接收它并通知所有用户这个特定用户有一个新的信用。
在下面的代码中,我检查if (!snapshot.exists(),如果不存在,我使用admin.database().ref('/user_credits/{creditId}/{userId}').set({ dict }); 将节点添加到数据库中。粘贴网址后,我检查数据库,布局为:
我是一名 Swift 开发人员。在 Swift 中,我可以这样做:
Database.database().reference().child("/user_credits/\(creditId)/\(userId)").setValue(dict) and the tree will be correct.
user_credits > {creditId} > {userId} > dict 不正确。应该是user_credits > sample_123 > user_xyz > dict values。我哪里出错了?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateViewsCtAtPostsRef = functions.https.onRequest((request, response) => {
const currentTimeStamp = Date.now();
const receivedTimeStamp = admin.database.ServerValue.TIMESTAMP;
const creditId = "sample_123";
const userId = "userId_xyz";
admin.database().ref('user_credits').child(creditId).child(userId).once('value', snapshot => {
if (!snapshot.exists()) {
var dict = {
"joined_date": receivedTimeStamp,
"timeStamp": receivedTimeStamp,
"credits_count": 1
};
return admin.database().ref('/user_credits/{creditId}/{userId}').set({ dict });
} else {
const previousTimeStamp = snapshot.child("timeStamp").val();
const creditsCount = snapshot.child("credits_count").val();
if (previousTimeStamp + whatever) < currentTimeStamp {
let updatedCount = creditsCount + 1
return admin.database().ref('/user_credits/{creditId}/{userId}').update({ "timeStamp": receivedTimeStamp, "credits_count": updatedCount });
} else {
return true
}
}
});
});
【问题讨论】:
-
如果是语法问题,那么您的代码会产生错误 - JavaScript 不会在语法错误的情况下运行。请编辑问题以显示该错误。如果没有错误,则说明其他错误。在这种情况下,添加一些日志记录并显示您从该调试中学到了什么。
-
哦,好吧,这一定不是语法问题,我会从问题中删除它,我以为是
-
我还注意到您的函数从不向客户端发送响应,这是所有 http 函数所必需的。请编辑问题以说明此函数在调用时应该实际执行的操作。
-
好的,请稍等,我是云功能的新手。我昨天才开始使用它们
标签: javascript firebase-realtime-database google-cloud-functions