Back

Technologies:

javascriptjavascript
avatar
Tolerim
2 hours ago

What is the method for dividing values in a realtime database using cloud functions?

As a beginner in Cloud functions, I am working on creating a reminder and trying to retrieve the time values (stored as 'start at'). While I am able to access them, I am unable to split them individually to use in my Date object. Can you guide me on how to approach this? For reference, here is the code I am working with:
exports.scheduleremindernotifications = functions.database.ref('/users/{userId}/name').onCreate((snapshot, context) => {
  const usersRef = admin.database().ref('users');
  usersRef.once('value', (snapshot) => {
    snapshot.forEach((childSnapshot) => {
      const userId = childSnapshot.key;
      const consumingRef = admin.database().ref(`users/${userId}/missions`);
      consumingRef.once('value', (snapshot) => {
        snapshot.forEach((childSnapshot) => {
          const missions_keys = childSnapshot.key;

          // Start at time elde ettik.
          const startatref = admin.database().ref(`users/${userId}/missions/${missions_keys}/startat`);

          startatref.once('value').then(allToken => {
            if (allToken.val()) {
              const token = allToken.val();

              console.log(`${token}`);

              // Outputs:  6 5 2023 6 8 13 UTC+3 , 6 5 2023 6 8 13 UTC+3

              // I should split it all according to (" ") space such as:
              //  first[0]
              // second[1]
              // third[2]

              const date23 = new Date(first[0] + '/' + second[1] + '/' + third[2]).setHours(17, 30, 0);
            }
          });
        });
      });
    });
  });
Additionally, here is the firebase database structure for reference: enter image description here
Answers(1)
avatar
Tolerim
2 hours ago
Verified Answer
To split the startat string by space, you can use the split() method, like this:
const startatref = admin.database().ref(`users/${userId}/missions/${missions_keys}/startat`);

startatref.once('value').then(allToken => {
  if (allToken.val()) {
    const token = allToken.val();

    console.log(`${token}`);

    const tokens = token.split(' ');

    const first = tokens[0].split('/');
    const second = tokens[1].split(':');
    const third = tokens[2].split(':');

    const date23 = new Date(first[2], first[1] - 1, first[0], second[0], second[1], third[0]);
    
    console.log(date23); // Outputs a Date object for the given date and time.
  }
});
In this updated code, we split the startat string by space using the split() method. Then, we split the resulting tokens by / (for the date parts) and : (for the time parts). We use these parts to create a new Date object that represents the date and time we want to use. Note that we substract 1 from the month (first[1] - 1) because Date objects use 0-based indexing for months (i.e., January is 0, February is 1, and so on).
;