Firebase云功能:删除特定节点/数据

时间:2017-10-21 18:09:45

标签: node.js firebase firebase-realtime-database

我有一个聊天室的Firebase数据库&我想删除聊天室,当他们通过HTTPS触发器或任何触发器达到一定年龄(比如12小时)时。 我所有的聊天室都有一个timeCreated属性,&我找到了一些删除数据的示例,但我的所有数据都被删除了。

我的猜测是我没有走向正确的道路或其他什么。整个“chat_rooms”节点被删除,而不仅仅是我想要的单个旧聊天室。

我的nodeJS / Firebase CF代码

screenshot

我的数据库结构

database structure

JSON FILE

{
  "chat_rooms" : {
    "room1" : {
      ".priority" : "9y1btvc14n",
      "g" : "9y1btvc14n",
      "l" : [ 33.8696853, -98.534908 ],
      "timeCreated" : 1508634704
    },
    "room A" : {
      ".priority" : "9y1btvc161",
      "chat_messages" : {
        "-Kx0d6aU0vfcH3OuOI9X" : {
          "Nicholas R Castro" : "haha OMG"
        }
      },
      "g" : "9y1btvc161",
      "l" : [ 33.8697009, -98.5349073 ],
      "timeCreated" : 1508634797
    }
  },
  "usernames" : {
    "Mick Mastro" : "Knx3DCMTTZhDfgU3uBFpRQIQoJr1",
    "Rick Dastro" : "Tv6PkDZ2NpX3TPgcqEPg9LNSilR2"
  }
}

CloudFunction NodeJs文件

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

//the seconds since Jan 1, 1970 midnight
var seconds = new Date().getTime() / 1000;
const chatRoomsRef = functions.database.ref('chat_rooms');
const chatRoomsRef2 = admin.database().ref('chat_rooms');

exports.deletePractice = functions.https.onRequest((req,res)=>{
    var resultString = "Deleting these: ";
    chatRoomsRef2.once('value')
            .then(function(snapshot){
                        snapshot.forEach(function(childSnapShot){
                            var roomName = snapshot.key;
                            var uniqueRoomName = childSnapShot.key;
                            console.log(roomName); // "chat_rooms"
                            console.log(childSnapShot.key); // the unique room name

                            console.log(childSnapShot.child('timeCreated').val());
                            console.log(seconds);

                            if( ( seconds - childSnapShot.child("timeCreated").val() )  > 5){
                                const now = Date.now();
                                const cutoff = now - 5;
                                console.log("If statement passed3!");
                                const oldItemsQuery = chatRoomsRef2.orderByChild('timeCreated').endAt(cutoff);
                                return oldItemsQuery.once('value').then( snapshot => {
                                    //create a map with all the children need to be removed
                                    const updates = {};
                                    snapshot.forEach(child => {
                                        updates[child.key] = null;
                                    });
                                    return chatRoomsRef2.update(updates);
                                });

                            }
                        });
            });
res.status(200).send(resultString);
});

0 个答案:

没有答案