适用于Firebase的云功能child_added

时间:2017-03-28 22:57:08

标签: node.js firebase firebase-realtime-database google-cloud-functions

我正在为Firebase尝试Cloud Functions,创建一个函数,当新用户添加到数据库时(而不是在auth上),该函数将添加昵称。 从Firebase Documention我发现我需要使用:

ref.on("child_added", function(snapshot, prevChildKey) { 
    //Something
})

,但我甚至无法获得部署功能。我的代码是:

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)
})

有人可以帮助我吗?

更新

完成后,现在是我的代码:

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]
                });
            };
        };
    });
});

根据道格史蒂文森所回复的内容,我仍然需要弄清楚如果实际上有一个新的孩子被添加(新用户),该怎么做呢

1 个答案:

答案 0 :(得分:1)

我明白了。这是我使用的代码:

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);
        }
    });
});

我希望只在添加子项时调用它,而不是每次将某些内容写入数据库时​​(以限制使用)