【问题标题】:How can I get the value of children in Firebase database using Javascript?如何使用 Javascript 获取 Firebase 数据库中子项的值?
【发布时间】:2020-06-06 10:07:05
【问题描述】:

如何使用 javascript 获取 firebase 中特定键值对的值?我正在为 firebase 云消息传递创建一个函数。我的函数如下所示:

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/notifications/{receiver_user_id}/{notification_key}').onWrite((event, context)=>{
    const receiver_user_id = context.params.receiver_user_id;
    const notification_key = context.params.notification_key;
    console.log('We have a notification to send to : ', receiver_user_id);
    // Grab the current value of what was written to the Realtime Database.
    const snapshot = event.after.val();
    console.log('Uppercasing', context.params.notification_key, snapshot);
    console.log('original value : ', snapshot);

    if(!event.after.val()){
        console.log('A notification has been deleted: ', notification_key);
        return null;
    }

    const sender_fullname = admin.database().ref(`/notifications/${receiver_user_id}/{notification_key}/notifying_user_fullname`).once('value').toString();
    console.log('full name value : ', sender_fullname);

    const DeviceToken = admin.database().ref(`/tokens/${receiver_user_id}/device_token`).once('value');

        return DeviceToken.then(result=>{
        const token_id = result.val();
        console.log('token id value : ', token_id);

            const payload = {
            notification: {
                title: sender_fullname.toString(),
                body: "You have a new message!",
                icon: "default"
                }
            };

            return admin.messaging().sendToDevice(token_id, payload).then(response=>{
                console.log('Message has been sent');
            });

        });

});

现在 sender_fullname 在控制台日志和发送的通知中生成 [object Promise]。我不确定如何获得确切的价值。我的实时数据库中的示例条目如下所示:

original value :  { date_created: '02-21-2020T17:50:32',
  my_id: '0ntpUZDGJnUExiaJpR4OdHSNPkL2',
  notification_key: '-M0dwVL3w1rKyPYbzUtL',
  notification_type: 'liked',
  notifying_user: 'OiBmjJ7yAucbKhKNSHtYHsawwhF2',
  notifying_user_fullname: 'Captain Proton',
  post_key: '-LzSJrOq9Y7hGgoECHRK',
  read: 'false' }

有什么方法可以得到“notifying_user_fullname”的确切值?任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    要获得sender_fullname 的值,您必须完全按照为DeviceToken 所做的方式!

    once() 方法返回一个用DataSnapshot 解析的承诺,因此您需要使用then() 方法来获取DataSnapshot,然后使用val() 方法。

    所以以下应该可以解决问题(未经测试):

    exports.sendNotification = functions.database.ref('/notifications/{receiver_user_id}/{notification_key}')
        .onWrite((event, context) => {
            const receiver_user_id = context.params.receiver_user_id;
            const notification_key = context.params.notification_key;
            console.log('We have a notification to send to : ', receiver_user_id);
            // Grab the current value of what was written to the Realtime Database.
            const snapshot = event.after.val();
            console.log('Uppercasing', context.params.notification_key, snapshot);
            console.log('original value : ', snapshot);
    
            if (!event.after.val()) {
                console.log('A notification has been deleted: ', notification_key);
                return null;
            }
    
            let sender_fullname;
    
            return admin.database().ref(`/notifications/${receiver_user_id}/${notification_key}/notifying_user_fullname`).once('value')
                .then(dataSnapshot => {
    
                    sender_fullname = dataSnapshot.val();
                    return admin.database().ref(`/tokens/${receiver_user_id}/device_token`).once('value');
    
                })
                .then(dataSnapshot => {
    
                    const token_id = dataSnapshot.val();
                    console.log('token id value : ', token_id);
    
                    const payload = {
                        notification: {
                            title: sender_fullname,
                            body: "You have a new message!",
                            icon: "default"
                        }
                    };
    
                    return admin.messaging().sendToDevice(token_id, payload)
    
                })
                .then(() => {
                    console.log('Message has been sent');
                    return null;  // <-- Note the return null here, to indicate to the Cloud Functions platform that the CF is completed
                })
                .catch(error => {
                    console.log(error);
                    return null;
                })
    
        });
    

    注意我们如何链接异步方法返回的不同承诺,以便在云函数中返回一个 Promise,这将向平台指示云函数工作已完成。

    我建议你观看Firebase video series 中关于“JavaScript Promises”的 3 个视频,这说明了这一点的重要性。

    【讨论】:

    • 这很有帮助,我试了一下,效果很好。我以前没有真正使用过 Javascript,文档有时让我有点困惑。感谢您清理它并帮助我解决问题。也感谢您提供的视频链接。为你干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2023-03-22
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多