Google Cloud Function OnWrite如何获取刚添加的孩子

时间:2018-07-09 13:55:55

标签: javascript google-cloud-functions

我正在尝试仅在数据库中获取新添加的子项,因此我尝试从snapshot.before中减去snapshot.after。不幸的是,这个没有用。我的代码如下:

const functions = require('firebase-functions');
    // 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.gameLoopBeing = functions.database.ref('/Chat/{pushId}')
    .onWrite((snapshot, context) => {
    //I want to retrieve the pushID        
    const original = snapshot.before.val();
    const newValue = snapshot.after.val();
    const difference = newValue-original
    console.log('alool',context.params.pushId, difference);
    // const uppercase = original.toUpperCase();
    return snapshot.ref.set(original);
});

1 个答案:

答案 0 :(得分:0)

如果要从函数中获取新添加的数据,则需要执行此操作;

exports.gameLoopBeing = functions.database.ref('/Chat/{pushId}').onWrite((snapshot, context) => {
  if (snapshot.after.exists() && !snapshot.before.exists()) {
    const new_data = snapshot.after.val();
  } else {
    return null;
  }
});