Reputation: 179
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?
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)
Upvotes: 3
Views: 2850
Reputation: 179
I figured it out. Here's the code I used:
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var childs = [];
var nicknames = [];
exports.newUser = functions.database.ref('users').onWrite(event => {
ref.on("child_added", function(snapshot, childKey) {
if (!childs.includes(childKey)) {
childs.push(childKey);
}
});
});
I would like it only to be called when a child is added and not every time something is written to the database (to limit usage)
Upvotes: 1