Firebase云功能:从其他节点访问数据

时间:2017-10-13 05:55:03

标签: firebase firebase-cloud-messaging google-cloud-functions

  1. 尝试实现:通过firebase云功能从单独的节点提取数据
  2. 处理: onCreate on / users / {uid},它为我提供了一个managedby密钥,使用该密钥访问另一个/ users / uid。
  3. 错误:(错误1):TypeError无法读取null的属性“name”。 (更新1):代码存在两个问题(a)我没有使用$ sign for $ {managedby}而第二个没有在const managerVal中使用“.then”。 (错误2):抛出的新错误是:admin.database.ref(..)。然后不是exports.sendWelcomeEmail中的函数...我在别处读过我们不应该在函数中使用admin。那么替代方案是什么?错误3:查看下面的ERROR 2更新。我认为它必定是一个很小的东西。
  4. 名称的值为。这里有什么根本错误吗? (清除。阅读更新1)

        admin.initializeApp(functions.config().firebase);
        // // Create and Deploy Your First Cloud Functions
        // // https://firebase.google.com/docs/functions/write-firebase-functions
        //
        // exports.helloWorld = functions.https.onRequest((request, response) => {
        //  response.send("Hello from Firebase!");
        // });
    
        exports.sendWelcomeEmail = functions.database.ref('/users/{uid}').onWrite(event => {
            if (!event.data.exists() || event.data.previous.exists()) {
                return;
            }
    
            var user = event.data.val()
            var {email} = user
            var {managedby} = user
            const managerVal = admin.database().ref(`/users/{managedby}`).on('value', function(snapshot){
                    const managedByName = snapshot.val().name
                    const managedByMobile = snapshot.val().mobile
            });
    
    
            console.log(email)
    
            var data = {
    
                from: 'no-reply@firebaseapp.com',
                subject: 'From Your Admin! Please set your Password for your account',
                html: `<p> hello</p>`,
                to: email
            }
    
            mailgun.messages().send(data, function (error, body) {
                console.log(body)
            })
    
        });
    
  5. 错误2:更新:我使用了@ faruk的方法:

    var user = event.data.val();
        var email = user.email;
        var managedby = user.managedby;
        const managerVal = db.ref('/users/' + managedby).on('value', function(snapshot){
            console.log("inside the function")
            const managerUser = snapshot.val();
            if(managerUser)
            {
                const managedByName = managerUser.name;
                const managedByMobile = managerUser.mobile;
            }
        });
        console.log("outside the function")
    

    我也尝试过使用.then

    var user = event.data.val();
    var email = user.email;
    var managedby = user.managedby;
    const managerVal = db.ref('/users/' + managedby).once('value')
        .then((snapshot) => {
        console.log("inside the function")
        const managerUser = snapshot.val();
        if(managerUser)
        {
            const managedByName = managerUser.name;
            const managedByMobile = managerUser.mobile;
        }
    });
    
    console.log("outside the function")
    

    现在的问题是,“函数外部”部分首先被触发,然后“函数内部”部分被触发。在函数离开之前,函数内的执行是否先完成?我不知道问题出在哪里。

    The screegrab from the firebase console

    编辑:Faruk,我已经在你显示的数据库调用中放入(复制粘贴)整个邮件程序功能。一些非常基本的东西正在被遗漏。仍然会收到此错误:

    enter image description here

    错误2:更新2:我刚刚使用.then,代码就是这个。

     var db = admin.database();
        if (!event.data.exists() || event.data.previous.exists()) {
            return;
        }
        var user = event.data.val();
        var email = user.email;
        var managedby = user.managedby;
        console.log(managedby)
        const managerVal = db.ref('/users/' + managedby).once('value')
    
        managerVal.then((snapshot) => {
            const managerUser = snapshot.val()
            console.log("inside snapshot")
            if (managerUser) {
                console.log("deep inside snapshot")
                const managedByName = managerUser.name
                const managedByMobile = managerUser.mobile
            }
        })
            console.log("outside snapshot")
            console.log('managerName = ' + managedByName)
            console.log('email = ' + email)
    

    这是它在仪表板中的特色(在下面的屏幕截图中给出)。考虑到它的复杂程度,我认为它必须是一个真正简单的解决方案。

    enter image description here

1 个答案:

答案 0 :(得分:2)

也许是这样的:

const admin = require('firebase-admin');
var serviceAccount = require("./serviceAccountKey.json");

//just called once
admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://[your_project_id].firebaseio.com"
});

exports.sendWelcomeEmail = functions.database.ref('/users/{uid}').onCreate(event => {
    var db = admin.database();
    if (!event.data.exists() || event.data.previous.exists()) {
        return;
    }

    var user = event.data.val();
    var email = user.email;
    var managedby = user.managedby;
    const managerVal = db.ref('/users/' + managedby).on('value', function(snapshot){
            const managerUser = snapshot.val();
            var managedByName;
            var managedByMobile;
            if(managerUser)
            {
              managedByName = managerUser.name;
              managedByMobile = managerUser.mobile;
            }
            console.log('managerName = ' + managedByName);
            console.log('email = ' + email);

            var data = {
               from: 'no-reply@firebaseapp.com',
               subject: 'From Your Admin! Please set your Password for your account',
               html: `<p> hello</p>`,
               to: email
            }

            mailgun.messages().send(data, function (error, body) {
              console.log(body)
            })

    });


});

on Value始终以异步方式工作