A' days'超过1个孩子的节点不会被删除。我该如何解决这个问题?
我需要确保我的承诺在顶层冒泡到最后一个()。所以我需要在collectionRef.once
之前返回。但是,返回语句现在可以阻止collectionRef.once
发生。我被困了!
这是我的代码
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; // ILEGAL RETURN STATEMENT
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 :(得分:0)
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 = defaultDatabase.ref().child('/days')
// return collectionRef // ILEGAL RETURN STATEMENT
collectionRef.once('value').then(messagesData => {
console.log(`Hello messageData : ${messagesData.numChildren()}`)
if(messagesData.numChildren() > 1) {
const 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)!
}
})
})
使用defaultDatabase.ref().child('/days')
而不是event.data.ref.parent
还请仔细阅读文档,了解promises如何运作,它将帮助您将来。现在这些更改都会有效。我的结尾已经过了。
您必须观看的视频
What's the difference between event.data.ref and event.data.adminRef? - #AskFirebase Asynchronous Programming (I Promise!) with Cloud Functions for Firebase - Firecasts
您可以订阅他们的Firebase YouTube Channel以获取最新更新并了解详情。