在Firebase云函数中经过特定日期后,如何删除子节点? [英] 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
所以我创建了一个Firebase云函数,在其中我将现在的时间(Date().now)与数据库中的时间戳进行比较
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
下面是代码:
// // 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使用间隔/时间戳(以秒为单位),小数部分表示亚秒级细节.大多数其他平台使用毫秒.这意味着两个值之间存在1000倍的差异,这说明了为什么您的比较无法正常工作.
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.
最简单的解决方法是将其乘以1000或除以1000.例如
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)
}
这篇关于在Firebase云函数中经过特定日期后,如何删除子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!