【问题标题】:Node with more than 1 child is not getting removed? [duplicate]超过 1 个子节点的节点没有被删除? [复制]
【发布时间】:2017-11-28 08:06:51
【问题描述】:

具有超过 1 个子节点的“天”节点不会被删除。我该如何解决这个问题?

下面是我的代码(最初来自here):

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

});

数据结构:

【问题讨论】:

  • 您没有从上一个 then() 返回任何内容。 Michael 在他对your previous question 的回答中向您展示了如何做到这一点。我建议在 this documentationthis videothis blog post 中学习更多关于 Promises 的知识。
  • @FrankvanPuffelen 我应该在哪里以及如何在我的代码中添加 return 语句?
  • @FrankvanPuffelen 我添加了一个return,仍然无法正常工作。查看更新后的问题。
  • 您需要确保您的承诺冒泡到顶层的最后一个then()。所以你在collectionRef.once之前需要另一个return
  • @FrankvanPuffelen 查看编辑。还是不行……

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

要使您的代码正常工作,只需替换以下行:-

return collectionRef;
collectionRef.once('value').then(messagesData => {

使用以下内容:-

return collectionRef.once('value').then(messagesData => {

这样做的原因是return collectionRef 中的return 语句阻止了进一步的代码执行。取而代之的是,您必须按照我建议的替换中所做的那样返回 promise(action)。

这应该可以立即解决您的问题,但是正如 Frank van Puffelen 在他的 cmets 中提到的,学习 Promise 的概念将对您将来有很大帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多