如何在Cloud Functions for Firebase中检查节点的子节点数是否大于1?在我的情况下,我想看看天数是否> 1
例如:
if(children of 'messages' node > 1)
// do something
答案 0 :(得分:1)
三种选项,具体取决于您的使用案例:
一个。检索messages
对象并计算密钥,例如
var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2
两个。更有利的是,将count
节点保留为messages
的子节点,并监控添加和删除子项的时间。 Firebase提供了一个如何执行此操作的示例:
<强>三即可。您还可以使用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