检查孩子的数量是否大于1

时间:2017-06-29 12:29:39

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

如何在Cloud Functions for Firebase中检查节点的子节点数是否大于1?在我的情况下,我想看看天数是否> 1

例如:

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

enter image description here

2 个答案:

答案 0 :(得分:1)

三种选项,具体取决于您的使用案例:

一个。检索messages对象并计算密钥,例如

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

from here

两个。更有利的是,将count节点保留为messages的子节点,并监控添加和删除子项的时间。 Firebase提供了一个如何执行此操作的示例:

Here

<强>三即可。您还可以使用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
        }
    })
});

答案 1 :(得分:0)

如果您打算一周中只使用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