I'm trying out Cloud Functions for Firebase, creating a function which will add a nickname when a new user is added to the database (not on auth). From the Firebase Documention I've found that I need to use:
ref.on("child_added", function(snapshot, prevChildKey) { //Something }) , but I cannot even get the function to deploy. My code is:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); var ref = admin.database().ref("/users"); ref.on("child_added", function(snapshot, prevChildKey) { console.log(snapshot) }) Can someone help me?
Update:
After working on it this is now my code:
const functions = require('firebase-functions'); // Import Admin SDK var admin = require("firebase-admin"); admin.initializeApp(functions.config().firebase); var db = admin.database(); var ref = db.ref('users'); var childs = []; var nicknames = []; exports.newUser = functions.database.ref('users').onWrite(event => { const data = event.data.val(); ref.on("child_added", function(snapshot, childKey) { if (!childs.includes(childKey)) { childs.push(childKey); }; for (i in childs) { if (childs[i] == null) { childs.splice(i, 1); }; }; }); ref.once("value", function(snapshot) { for (i in childs) { var child = data[childs[i]]; if (!child.hasOwnProperty("nickname")) { console.log("Child does not have nickname: " + childs[i]); ref.child(childs[i]).update({ nickname: "user"+childs[i] }); }; }; }); }); Based on what Doug Stevenson has replied, I still need to figure out how to only do this if there's actually a new child being added (new user)