Firebase Cloud Functions可立即删除节点,而不是2小时后删除 [英] Firebase Cloud Functions is deleting nodes instantly instead of deleting after 2 hours

查看:46
本文介绍了Firebase Cloud Functions可立即删除节点,而不是2小时后删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Cloud Functions在Firebase上2小时后删除节点.但是,当我添加一个节点时,一旦在数据库中创建该节点,它就会被删除

I'm using Cloud Functions to delete nodes after 2 hours on firebase.However, when I add a node, it is being deleted as soon as it is created inside the database

我的index.js:

My index.js:

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

const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds
exports.deleteOldItems = functions.database.ref('/posts/{randomID1}/{randomID2}/timestamp')
.onWrite(function(change) {
    var ref = change.after.ref.parent; // reference to the parent
    var now = Date.now();
    var cutoff = now - CUT_OFF_TIME;
    var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
    return oldItemsQuery.once('value').then(function(snapshot) {
      // create a map with all children that need to be removed
      var updates = {};
      snapshot.forEach(function(child) {
        updates[child.key] = null;
      });
      // execute all updates in one go and return the result to end the function
      return ref.update(updates);
    });
  });

我的数据库结构:

  "posts" : {
    "randomID1" : {
      "randomID2" : {
        "timestamp" : 1557842159
      }
    },
    "randomID3" : {
      "randomID4" : {
        "timestamp" : 1557842203
      }
    },

推荐答案

您正在比较以毫秒为单位的时间戳和以秒为单位的时间戳.

You are comparing timestamp in milliseconds with timestamp in seconds.

var cutoff = now - CUT_OFF_TIME;-截止值以毫秒为单位

var cutoff = now - CUT_OFF_TIME; - The cutoff value is in milliseconds

您需要更改CUT_OFF_TIME并将Date.now()转换为秒.

You need to change the CUT_OFF_TIME and convert Date.now() to seconds.

这篇关于Firebase Cloud Functions可立即删除节点,而不是2小时后删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆