【发布时间】:2017-11-28 08:06:51
【问题描述】:
具有超过 1 个子节点的“天”节点不会被删除。我该如何解决这个问题?
下面是我的代码(最初来自here):
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const defaultDatabase = admin.database();
exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}')
.onWrite(event => {
var ref = event.data.ref.parent; // reference to the items
var now = Date.now();
var cutoff = now - 2 * 60 * 60 * 1000;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
return oldItemsQuery.once('value', 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);
}).then(function() {;
const theRef = event.data.ref;
const collectionRef = theRef.parent.child('days');
return collectionRef;
collectionRef.once('value').then(messagesData => {
if(messagesData.numChildren() > 1) {
let updates = {};
updates['/days'] = null;
return defaultDatabase.ref().update(updates); // 'days' doesn't get removed even if it has more than 1 child (as in the image)!
}
})
});
});
数据结构:
【问题讨论】:
-
您没有从上一个
then()返回任何内容。 Michael 在他对your previous question 的回答中向您展示了如何做到这一点。我建议在 this documentation、this video 和 this blog post 中学习更多关于 Promises 的知识。 -
@FrankvanPuffelen 我应该在哪里以及如何在我的代码中添加 return 语句?
-
@FrankvanPuffelen 我添加了一个
return,仍然无法正常工作。查看更新后的问题。 -
您需要确保您的承诺冒泡到顶层的最后一个
then()。所以你在collectionRef.once之前需要另一个return。 -
@FrankvanPuffelen 查看编辑。还是不行……
标签: javascript node.js firebase firebase-realtime-database google-cloud-functions