如何根据子云函数删除 Firebase 中的某个父节点
How do I remove a certain parent node in Firebase based on a child Cloud functions
我目前的数据库结构是这样的
我想要做的是能够遍历每个具有特定 feedId 的文件,我一直在尝试这种方式,但目前没有运气。有人能帮忙吗?
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
})
}
您当前正在从内部回调返回快照。由于这不是一个承诺,它会立即解决 - 并且您的功能将被终止。在删除节点之前。
最简单的修复方法是使用 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);
})
}
或者,您可以使用多路径更新通过一次写入擦除所有匹配的节点:
function clearAllPostsInOwnFeed(userId) {
const ref = admin
.database()
.ref(constants.FBC_USERS_FEEDS + '/' + userId);
return ref
.once('value')
.then((snapshot) => {
let updates = {};
snapshot.forEach((snap) => {
if (snap.child('fromId').val() === userId) {
updates[snap.key] = null;
}
})
return ref.update(updates);
})
}
我目前的数据库结构是这样的
我想要做的是能够遍历每个具有特定 feedId 的文件,我一直在尝试这种方式,但目前没有运气。有人能帮忙吗?
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
})
}
您当前正在从内部回调返回快照。由于这不是一个承诺,它会立即解决 - 并且您的功能将被终止。在删除节点之前。
最简单的修复方法是使用 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);
})
}
或者,您可以使用多路径更新通过一次写入擦除所有匹配的节点:
function clearAllPostsInOwnFeed(userId) {
const ref = admin
.database()
.ref(constants.FBC_USERS_FEEDS + '/' + userId);
return ref
.once('value')
.then((snapshot) => {
let updates = {};
snapshot.forEach((snap) => {
if (snap.child('fromId').val() === userId) {
updates[snap.key] = null;
}
})
return ref.update(updates);
})
}