Firebase云功能未按预期删除旧节点

时间:2019-06-06 14:03:44

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

我正在使用Firebase Cloud Functions删除Firebase数据库中的旧节点。大约1个月前,我问一个similar question,问题是值是几秒钟而不是毫秒,但问题仍然存在。如何解决此问题?

我的index.js:

'use strict';

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

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 30000; // 30 seconds in milliseconds.

/**
 * This database triggered function will check for child nodes that are older than the
 * cut-off time. Each child needs to have a `timestamp` attribute.
 */
exports.deleteOldItems = functions.database.ref('/posts/{id1}/{id2}/timestamp').onWrite(async (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);
  var snapshot = await oldItemsQuery.once('value');
  // create a map with all children that need to be removed
  var updates = {};
  snapshot.forEach(child => {
    updates[child.key] = null;
  });
  // execute all updates in one go and return the result to end the function
  return ref.update(updates);
});

和我的数据库结构

  "posts" : {
    "38d1d0aa-d774-4a69-a78e-44d02b285669" : {
      "-LggzAxeAYXF7tOav_vF" : {
        "timestamp" : 1559827888988
      }
    },
    "58fe50ae-db93-4a22-996f-7a28d82583ba" : {
      "-Lggze2bvHZx2gJeM8OA" : {
        "timestamp" : 1559828012239
      }
    }
  },

0 个答案:

没有答案