所以下面是我的firebase数据库的JSON:
{
"1YrpX2W2xnMPoy4YGpZcOE0xJ5g2" : {
"email" : "muyi@hotmail.com",
"fullname" : "Muyiz",
"selection" : [ 1, 2, 3, 4, 5, 6 ],
"teamname" : "awon",
"total" : 12,
"userName" : "motmail.com",
"week1" : 0,
"week10" : 0,
"week11" : 0,
"week12" : 0,
"week2" : 0,
"week3" : 0,
"week4" : 0,
"week5" : 0,
"week6" : 12,
"week7" : 0,
"week8" : 0,
"week9" : 0
},
"6K9rQiZQ3jaV38WWtDbNwxhqIwc2" : {
"email" : "domi@gmail.com",
"fullname" : "Dai",
"selection" : 0,
"teamname" : "Bayern Neverlosin'",
"total" : 0,
"userName" : "dai@gmail.com",
"week1" : 0,
"week10" : 0,
"week11" : 0,
"week12" : 0,
"week2" : 0,
"week3" : 0,
"week4" : 0,
"week5" : 0,
"week6" : 0,
"week7" : 0,
"week8" : 0,
"week9" : 0
},
"9OgN4HyMtARaQEQV1mKQ5lyE1992" : {
"email" : "jonail.com",
"fullname" : "Jon",
"selection" : [ 40, 8, 10, 24, 18, 34 ],
"teamname" : "Chad fc",
"total" : 0,
"userName" : "jojin@gmail.com",
"week1" : 0,
"week10" : 0,
"week11" : 0,
"week12" : 0,
"week2" : 0,
"week3" : 0,
"week4" : 0,
"week5" : 8,
"week6" : 0,
"week7" : 0,
"week8" : 0,
"week9" : 0
},
"AGVZAUye5ZbZgvwCOpMeDkoOsEU2" : {
"email" : "ihe@gmail.com",
"fullname" : "Emeka Iheme",
"selection" : 0,
"teamname" : "Young Money",
"total" : 0,
"userName" : "ihem@gmail.com",
"week1" : 0,
"week10" : 0,
"week11" : 0,
"week12" : 0,
"week2" : 0,
"week3" : 0,
"week4" : 0,
"week5" : 0,
"week6" : 0,
"week7" : 0,
"week8" : 0,
"week9" : 0
}
}
以下是我使用过的云功能:
exports.update = functions.database.ref('/users/{user.uid}')
.onWrite(event=>{
console.log ('it banged!');
const uid = event.data.key;
ref = admin.database().ref(`/users/`+ uid + `week1`);
pref1 = admin.database().ref("Player").child("playerweek8");
ref2 = admin.database().ref(`/users/` + uid `/` );
if(n === 4){
ref.set(10);
}
问题
问题是代码仅在相应用户发生更改时才起作用。例如,如果我使用uid 1YrpX2W2xnMPoy4YGpZcOE0xJ5g2
更改用户的写入,则会将10设置为ref。但我的目标是更改用户节点,以便为每个用户生成ref.set(10)
。这不可能吗?对不起你可能猜到,我是firebase的新手。提前谢谢。
答案 0 :(得分:3)
如果您不熟悉Firebase和JavaScript,Firebase的Cloud Functions不是学习它的最佳方式。我建议先阅读Firebase documentation for Web developers和/或Firebase codelab for Web developer。它们涵盖了许多基本的JavaScript,Web和Firebase交互。在那些之后,您将更好地为云功能编写代码。但我会尝试解释为什么您的代码无法正常工作以及我将如何处理它。
您正在使用数据库触发器,只有在对数据库的写入与您指定的条件匹配时才会调用该数据库触发器。所以你的:
exports.update = functions.database.ref('/users/{user.uid}').onWrite(
仅在写入用户节点时触发。
如果您想对所有用户进行批处理,您可能需要使用HTTP触发器:
exports.updateUsers = functions.https.onRequest((req, res) => {
...
});
部署此功能时,它会为您提供一个URL。您可以通过调用URL或只是在浏览器中打开它来触发该功能。
在该功能中,您希望从数据库加载用户并处理它们。总数将为您留下如下内容:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateUsers = functions.https.onRequest((req, res) => {
admin.database().ref("users").once("value").then((snapshot) => {
snapshot.forEach((userSnap) => {
userSnap.child("week1").set(10);
});
});
});
您需要根据需要修改功能中的代码。我主要关注的是主要概念:通过HTTP触发,然后从数据库加载数据。