繁体   English   中英

检查孩子人数是否大于1

[英]Check if number of children greater than 1

如何在Cloud Functions for Firebase中检查节点的子代数目是否大于1? 就我而言,我想看看天数是否> 1

例如:

if(children of 'messages' node > 1)
// do something

在此处输入图片说明

三个选项,取决于您的用例:

一。 检索messages对象并计算键,例如

var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2

从这里


二。 更有利的是,将count节点保留为messages的子级,并监视何时添加和删除子级。 Firebase提供了有关如何执行此操作的示例:

这里


您也可以将numChildren()用于快照的顶层。

numChildren

例:

// If the number of likes gets deleted, recount the number of likes
exports.countDays = functions.database.ref('/messages').onWrite(event => {
    const theRef = event.data.ref;
    const collectionRef = theRef.parent.child('days');
    collectionRef.once('value').then(messagesData => {
        if(messagesData.numChildren()) > 1) {
            // do something
        }
    })
});

如果您计划仅使用一周的7天,则可以使用一周的日期循环遍历数组,并执行以下操作:

function amountOfChildren(ref, arr) {
  let children = 0;
  for (const item in arr) {
    if ref.hasChild(item) {children++}
  }
  return children;
}

const rootRef = firebase.database().ref();
const daysRef = rootRef.child('days');
const weekDays = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];
amountOfChildren(daysRef, weekDays); // returns a number from 0 to 7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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