没有删除包含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)!
}
})
});
});
数据结构:
答案 0 :(得分:1)
要使代码正常工作,只需替换以下行: -
return collectionRef;
collectionRef.once('value').then(messagesData => {
具有以下内容: -
return collectionRef.once('value').then(messagesData => {
这样做的原因是return collectionRef
中的return语句阻止了进一步的代码执行。而不是那样,你必须按照我建议的替换方式返回promise(action)。
这应该可以解决你现在的问题,但正如Frank van Puffelen在评论中提到的那样,学习承诺的概念将在未来对你有很大的帮助!