简体   繁体   中英

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

I currently have my DB structure like thisfirebase 实时数据库结构

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM