Home > Net >  How do I remove a certain parent node in Firebase based on a child Cloud functions
How do I remove a certain parent node in Firebase based on a child Cloud functions

Time:10-22

I currently have my DB structure like this firebase realtime database structure

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. 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
  })
}

CodePudding user response:

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:

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);
  })
}
  • Related