删除日期后的项目(Firebase 云功能)



我正在尝试编写一个Firebase云函数,以便在日期过后自动删除事件。

基于这个Firebase示例,我得出了这个,但是当我将其上传到Firebase时,它正在Firebase端运行,但它不会删除事件。

你们有建议或看到我的代码有问题吗?问题是否可能来自触发onWrite()

/* My database structure
/events
item1: {
MyTimestamp: 1497911193083
},
item2: {
MyTimestamp: 1597911193083                    
}
...
*/
// Cloud function to delete events after the date is passed
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.deleteOldItems = functions.database.ref('/events/{eventId}').onWrite((change) => {

const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const oldItemsQuery = ref.orderByChild('MyTimestamp').endAt(now);
return oldItemsQuery.once('value').then((snapshot) => {
// create a map with all children that need to be removed
const updates = {};
	snapshot.forEach(child => {
		updates[child.key] = null;
	});
return ref.update(updates);
// execute all updates in one go and return the result to end the function
});
});

代码没有问题,只需更新您的云函数和管理员:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.deleteOldItems = functions.database.ref("/events/{eventId}").onWrite((change, context) => {
if (change.after.exists() && !change.before.exists()) {
const ref = change.after.ref.parent;
const now = Date.now();
const oldItemsQuery = ref.orderByChild('MyTimestamp').endAt(now);
return oldItemsQuery.once('value').then((snapshot) => {
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
return ref.update(updates);
});
} else {
return null;
}
});

在函数文件夹中运行以下命令:

npm install firebase-functions@latest --save npm install firebase-admin@5.11.0 --save

有关更多详细信息,请参阅此处

尝试更改

admin.initializeApp();

自:

admin.initializeApp(functions.config().firebase);