简体   繁体   中英

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

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" } } } 

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. Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM