[英]How do I remove a certain parent node in Firebase based on a child Cloud functions
I currently have my DB structure like this我目前有这样的数据库结构
What I want to do is be able to loop thorugh each one that has a certain feedId, I've been trying it this way but am currently having no luck.我想要做的是能够遍历每个具有特定 feedId 的循环,我一直在尝试这种方式,但目前没有运气。 Would anyone be able to assist?有人可以提供帮助吗?
function clearAllPostsInOwnFeed(userId) {
return admin
.database()
.ref(constants.FBC_USERS_FEEDS + '/' + userId)
.once('value')
.then((snapshot) => {
snapshot.forEach((snap) => {
if (snap.child('fromId').val() === userId) return snap.remove()
return snap
})
console.log(snapshot)
return snapshot
})
}
You're currently returning a snapshot from the inner callback.您当前正在从内部回调返回快照。 Since that is not a promise, it resolves right away - and your function gets terminated.由于这不是承诺,它会立即解决 - 您的功能将被终止。 before it has deleted the nodes.在它删除节点之前。
The simplest fix is to use Promise.all()
to wait for all deletes to finish:最简单的解决方法是使用Promise.all()
等待所有删除完成:
function clearAllPostsInOwnFeed(userId) {
return admin
.database()
.ref(constants.FBC_USERS_FEEDS + '/' + userId)
.once('value')
.then((snapshot) => {
let promises = []
snapshot.forEach((snap) => {
if (snap.child('fromId').val() === userId) {
promises.push(snap.ref.remove())
}
})
return Promise.all(promises);
})
}
Alternatively you can use a multi-path update to wipe all matching nodes with a single write:或者,您可以使用多路径更新通过一次写入擦除所有匹配的节点:
function clearAllPostsInOwnFeed(userId) {
const ref = admin
.database()
.ref(constants.FBC_USERS_FEEDS + '/' + userId);
return ref
.once('value')
.then((snapshot) => {
let updates = {};
snapshot.forEach((snap) => {
updates[snap.key] = null;
})
return ref.update(updates);
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.