Javascript 云功能-更新firebase数据库中的数据
我使用云函数来计算一篇文章上有多少评论。 当我添加注释时,它会将其保存在firebase数据库中,然后在云函数中,有一个函数会侦听“注释”节点,并将“+1”返回firebase数据库 出于某种原因,只有当我从firebase数据库中删除注释时,它才起作用。 当我删除注释时,添加“+1” 这是我的代码Javascript 云功能-更新firebase数据库中的数据,javascript,firebase,firebase-realtime-database,google-cloud-functions,Javascript,Firebase,Firebase Realtime Database,Google Cloud Functions,我使用云函数来计算一篇文章上有多少评论。 当我添加注释时,它会将其保存在firebase数据库中,然后在云函数中,有一个函数会侦听“注释”节点,并将“+1”返回firebase数据库 出于某种原因,只有当我从firebase数据库中删除注释时,它才起作用。 当我删除注释时,添加“+1” 这是我的代码 exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onWrite(event
exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onWrite(event =>{
const collectionRef = event.data.ref.parent;
const model = event.data.previous.val();
const commentid = event.params.commentid;
console.log("commentID:",commentid);
const countComments = collectionRef.child('countComments');
return countComments.transaction(current => {
console.log('Before the If');
if (!event.data.exists() && event.data.previous.exists()) {
console.log('Enter to the if.');
const commentsList = admin.database().ref(`comments/${commentid}/countComments`).transaction(current => {
return (current || 0) + 1;
});
}
}).then(() => {
console.log('Comments counter updated.');
});
});
任何人都可以告诉我我哪里做错了?您正在使用此选项来确定函数何时被触发:
exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onWrite(event =>{
这里的关键是使用onWrite
,这意味着对于/comments/{commentid}/{userUID}
下的任何写入操作都会触发此函数
由于您只添加到计数中,因此您的函数只应在添加新注释时运行。为此,您应该使用onCreate
而不是onWrite
:
exports.commentsCount = functions.database.ref('/comments/{commentid}/{userUID}').onCreate((snapshot, context) =>{
const collectionRef = snapshot.ref.parent;
const model = snapshot.val();
const commentid = context.params.commentid;
我还更新了参数以匹配1.0 Firebase函数库。有关更多信息,请参阅