user7889746
user7889746

Reputation:

Check if number of children greater than 1

How do I check if the number of children of a node is greater than 1 in Cloud Functions for Firebase? In my case I want to see if the number of days is > 1

For example:

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

enter image description here

Upvotes: 0

Views: 221

Answers (2)

theblindprophet
theblindprophet

Reputation: 7937

Three Options, depending on your use case:

One. Retrieve the messages object and count the keys, e.g.

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

from here


Two. More favorable, keep a count node as a child of messages and monitor when children are added and deleted. Firebase has provided an example on how to do that:

Here


Three. You can also use numChildren() for the top level of the snapshot.

numChildren

Example:

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

Upvotes: 1

mikat
mikat

Reputation: 1

If you plan on using just 7 days of the week you could just loop over an array with the week days and do this:

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

Upvotes: 0

Related Questions