snapshot.numChildren不是一个实时数据库触发器的功能

问题描述 投票:-1回答:2

我用我的火力地堡应用谷歌的云功能。我要算在文章的评论和更新在后称为comments_count性能的方法。

直到我升级了火力控制台和它的依赖关系这是工作就好了。现在,在日志中它说commentSnapshot.numChildren is not a function

在函数的代码看起来是这样的:

  //Function that updates comments count inside post
  exports.setCommentsCount =
      functions.database.ref('/Comments/{post_id}').onWrite((commentSnapshot, context) => {

        const post_id = context.params.post_id;
        const commentsCount = commentSnapshot.numChildren();

        //rest of code here
  }
javascript firebase firebase-realtime-database google-cloud-functions
2个回答
4
投票

你应该熟悉了发生在1.0版的云功能的火力地堡SDK为实时数据库触发器的breaking changes

onWrite触发不再接收DeltaSnapshot作为第一个参数为您提供的功能。它现在有Changebefore属性,每个属性是一个after对象DataSnapshot对象。这DataSnapshot有numChildren的方法:

functions.database.ref('/Comments/{post_id}').onWrite((change, context) => {
    const post_id = context.params.post_id;
    const commentsCount = change.after.numChildren();
}

0
投票

我遇到了同样的错误。因为numChildren()是DataSnapshot接口,但快照不是DataSnapshot你得到这个错误。下面是正确的代码:

'use strict';
const functions = require('firebase-functions');

const MAX_USERS = 10;

exports.truncate = functions.database.ref('/chat').onWrite((change) => {
  const parentRef = change.after.ref;
  const snapshot = change.after

  if (snapshot.numChildren() >= MAX_USERS) {
    let childCount = 0;
    const updates = {};
    snapshot.forEach((child) => {
      if (++childCount <= snapshot.numChildren() - MAX_USERS) {
        updates[child.key] = null;
      }
    });
    // Update the parent. This effectively removes the extra children.
    return parentRef.update(updates);
  }
  return null;
});
© www.soinside.com 2019 - 2024. All rights reserved.