node.js - 如何了解Firebase云函数中的新数据?

标签 node.js firebase google-cloud-functions

您如何知道数据是否没有变化以及 Firebase Cloud 功能有哪些新增功能?我尝试了几种不同的选项来标记如果数据刚刚更改,则我不会发送推送通知。我还尝试从快照 _newData 获取 和_data子 Node 的数量进行比较,如果__newData更大,那么这是一条新记录,但它不起作用。请告诉我如何做到这一点。

示例代码片段。

   module.exports = functions.database.ref('/userListEvents/{userID}')
        .onWrite(event => {

            const snapshot = event.data;

            if (event.data.val() && !event.data.previous.val()) {
                console.log('send push notification');
            } else if (snapshot._data) {
                console.log('send push notification');
            } else {
                return console.log('data was removed');
            };
    }

引用

functions.database.ref('/cards/{cardID}/interestedUsers')
    .onWrite(event => {

更新:此选项对我不起作用,因为如果我这样做 functions.database.ref ('/userListEvents/{userID}/{eventID}'),则会报告错误该字段不能为空。

我尝试过,但没有得到好的结果。

if (event.data.val() && !event.data.previous.val()) {
        console.log('send push notification');
    } else if (event.data.val() && event.data.previous.val()) {
        const newData = event.data.val();
        const previousData = event.data.previous.val();
        console.log('newData', newData, 'previousData', previousData);
        const newDataKeys = Object.keys(newData);
        const previousDataKeys = Object.keys(previousData);

        if (newDataKeys.length > previousDataKeys.length) {
            console.log('send push', newDataKeys.length, previousDataKeys.length);
        } else {
            return console.log('just update data', newDataKeys.length, previousDataKeys.length);
        }
    } else {
        return console.log('removed data')
    }

最佳答案

您需要使用 event.data.current.val() 而不是 event.data.val() 进行比较。示例:

exports.detectChange = functions.database.ref('/userListEvents/{userID}')
    .onWrite(event => {
        const crnt = event.data.current;
        const prev = event.data.previous;

        if (crnt.val() && !prev.val()) {
            // value created
            console.log('Created: send push notification');
        } else if (!crnt.val() && prev.val()) {
            // value removed
            console.log('Removed: send push notification');
        } else {
            // value updated
            console.log('Updated');
        }
     });

关于node.js - 如何了解Firebase云函数中的新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047431/

相关文章:

node.js - 从工件中删除旧文件后无法部署云功能

firebase函数:secrets:set is not a Firebase command

node.js - 在 express 中获取 rawBody

node.js - 用户登录时 Firebase 创建条目

node.js - Mongoose 可以为我提供某个领域的所有不同值(value)吗?

node.js - nodejs代理超时后不断开连接

node.js - Dialogflow v2 使用 Firebase Cloud Function 返回 Firestore 数据库数据

firebase - Flutter 从 QuerySnapshot 转换为 Future <List<Map<dynamic,dynamic>>>

flutter - 当 flutter 应用程序处于后台时,通知不会进入 Release模式

javascript - 使用 Firebase Cloud Functions 批量写入