How to remove a child node after a certain date is passed in Firebase cloud functions?

末鹿安然 提交于 2019-12-23 05:24:18

问题


So i have a database structure where i save an event with a timestamp value that dictates when the event will expire and be removed

so i created a firebase cloud function where i compare the time now (Date().now) with the timestamp in the database

the problem is when the code gets run the event gets removed immediately

here is the code:

// // 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!");
// });

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

exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const messagesRef = admin.database().ref('events')
    messagesRef.once('value', (snapshot) => {
        snapshot.forEach((child) => {
            child.forEach((child) => {
                if (Number(child.val()['endDate']) >= new Date().getTime()) {
                   child.ref.set(null)
              }
            })
        })
    })
    return res.status(200).end()
})
{   "events" : {
"N5iTuYzAbJa02RauxCl3uh2Nggz1" : {
  "-LNmIvSdrwK96KCGcmXm" : {
    "addedBy" : "Riyadh Figures",
    "coordinate" : [ 24.70914690943994, 46.78851541131735 ],
    "endDate" : "1538442801.0",
    "imagePath" : "-LNmIvSdrwK96KCGcmXm",
    "key" : "-LNmIvSdrwK96KCGcmXm",
    "title" : "hjihgf",
    "userPicture" : "N5iTuYzAbJa02RauxCl3uh2Nggz1"
  }
}   },   "user_profiles" : {
"N5iTuYzAbJa02RauxCl3uh2Nggz1" : {
  "email" : "riyadhfigures.official@gmail.com",
  "name" : "Riyadh Figures",
  "profile_picture" : "https://lh6.googleusercontent.com/-HfLRYyyTAxQ/AAAAAAAAAAI/AAAAAAAAAAA/AAN31DVNc5koC_GGuww6hxcMKPkx4niY-A/s96-c/photo.jpg"
},
"ah00Fe5hHnQM8tyceLE1xpWznUw1" : {
  "email" : "lenepouv@gmail.com",
  "name" : "Mbm Al Osaimi",
  "profile_picture" : "https://lh6.googleusercontent.com/-M0JCv0lMNTE/AAAAAAAAAAI/AAAAAAAAAIU/0M2Cef0YLOU/s96-c/photo.jpg"
},
"m1zj6gDEoUa9aCdPcazrb0rTuFj2" : {
  "email" : "mb.osaimi@gmail.com",
  "name" : "Mosab Al Osaimi",
  "profile_picture" : "https://lh5.googleusercontent.com/-X5va1C-uNpU/AAAAAAAAAAI/AAAAAAAAAAc/GVSZLwv46U0/s96-c/photo.jpg"
}   } }

回答1:


Swift uses intervals/timestamps in seconds with the fractional part indicating the subsecond details. Most other platforms use milliseconds. That means that there is a 1000x difference between the values, which explains why your comparison doesn't work.

The simplest fix is to multiple or divide by 1000. E.g.

if (1000*Number(child.val()['endDate']) >= new Date().getTime()) {
   child.ref.set(null)
}


来源:https://stackoverflow.com/questions/52600881/how-to-remove-a-child-node-after-a-certain-date-is-passed-in-firebase-cloud-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!