setted
setted

Reputation: 119

Firestore/Javascript: How to get document data using timestamps?

I'm trying to create a line graph for my project. To accomplish this I need two date inputs from a user. From there my backend takes the inputs converts it to a javascript date object.

My problem is when I'm trying to convert the date objects to a firestore timestamp I get this error.

TypeError: t.getTime is not a function at Function.ho.fromDate (timestamp.ts:27) at Object.next (generateReportDateRange.php:158) at subscribe.ts:104 at subscribe.ts:233

line (generateReportDateRange.php:158) pinpoints to this code:

var toTimeStampOne = firebase.firestore.Timestamp.fromDate(dateIdOne);

What that code does is to convert the date object to a firestore timestamp object. From there I am supposed to use toTimeStampOne as a query to get certain data from documents

here is the backend end code that may be related to the problem:

var dateIdOne = sessionStorage.getItem("dateOne");
var dateIdTwo = sessionStorage.getItem("dateTwo");

var dateSetArray = [];
var dataCal = [];

console.log(dateIdOne); //OUTPUT: Fri Mar 06 2020 08:00:00 GMT+0800 (Philippine Standard Time)
console.log(dateIdTwo); //OUTPUT: Tue Mar 10 2020 08:00:00 GMT+0800 (Philippine Standard Time)

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.userId = user.uid;
  } //stores the user id in variable
  var toTimeStampOne = firebase.firestore.Timestamp.fromDate(dateIdOne);
  var toTimeStampTwo = firebase.firestore.Timestamp.fromDate(dateIdTwo);
  var dateSetArray = [];
  var dataCal = [];
  let userRef1 = firebase.firestore().collection("users").doc(userId).collection("glucose")
    .where("dateAdded", ">=", toTimeStampOne)
    .where("dateAdded", "<=", toTimeStampTwo)
    .limit(7);
  return userRef1.get()
    .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        console.log(doc.id, " => ", doc.data());
        this.dateSet = doc.data().bgReading;

        dateSetArray.push(dateSet);

        this.calDateAdded = doc.data().dateAdded.toDate();
        const options = {
          month: 'short',
          day: 'numeric',
          year: 'numeric'
        };
        const date = new Date(calDateAdded);
        const americanDate = new Intl.DateTimeFormat('en-us', options).format(date);
        dataCal.push(americanDate);
      });
    });
});

EDIT

here is the process of the conversion

//get date input from the forms and converts it to a js date object already
    var data = {
            dateOne: new Date($('#dateRangeOne').val()), 
            dateTwo: new Date($('#dateRangeTwo').val()),
            };

//stores the date object to a session storage
sessionStorage.setItem("dateOne", data.dateOne);
sessionStorage.setItem("dateTwo", data.dateTwo);

Upvotes: 0

Views: 292

Answers (3)

setted
setted

Reputation: 119

I like to create the full code structure but I already marked an answer. Regardless I will post the code here because it might help other people.

Get input value from forms and use sessionStorage to carry it over to another page

<script>
(function(){
$('#dateForm').on('submit', async function (e) {
   e.preventDefault();
   var data = {
   dateOne: $('#dateRangeOne').val(),
   dateTwo: $('#dateRangeTwo').val(),//get date input
   };
   if(data.dateOne.getTime() == data.dateTwo.getTime()){
     alert("Please input a valid date range! Use the specific date generator to generate a daily report");
     window.location.href = "generateReport.php"; 
     }
   else if(data.dateOne.getTime() > data.dateTwo.getTime()){
      alert("Please input a valid date range!");
      window.location.href = "generateReport.php"; 
   }
   else{                              
        firebase.auth().onAuthStateChanged(function(user){
            if(user){
               this.userId = user.uid; //stores the userid
               console.log(userId);
            }
            sessionStorage.setItem("dateOne", data.dateOne);
            sessionStorage.setItem("dateTwo", data.dateTwo);
            setTimeout(function(){                    
                window.location.href = "generateReportDateRange.php"; 
            }, 3000);
            });
           }
          });
         })
       (); 
</script>

The query code (Getting document data based on two Firestore timestamp objects)

<script>
var dateIdOne = new Date(sessionStorage.getItem("dateOne"));
var dateIdTwo = new Date(sessionStorage.getItem("dateTwo"));

firebase.auth().onAuthStateChanged(user => {
  if(user){
    this.userId = user.uid;
  } //stores the user id in variable
var toTimeStampOne = firebase.firestore.Timestamp.fromDate(dateIdOne);
var toTimeStampTwo = firebase.firestore.Timestamp.fromDate(dateIdTwo);
let userRef1 = firebase.firestore().collection("users").doc(userId).collection("glucose")
.where("dateAdded", ">=", toTimeStampOne)
.where("dateAdded", "<=", toTimeStampTwo)
.limit(7);
//PERFORM GET DOC DATA HERE
});
</script>

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317808

I'm going to go ahead and make the call that your "date" object is not actually a JavaScript Date object. It's probably just a formatted string. You won't be able to work with this very effectively if you're trying to query Firestore timestamp fields.

You're probably going to need to change whatever the source of data is that's feeding these lines of code:

var dateIdOne = sessionStorage.getItem("dateOne");
var dateIdTwo = sessionStorage.getItem("dateTwo");

You'll need to make sure that sessionStorage.getItem returns something suitable for querying Firestore. That could be a proper date object, or some unix time in milliseconds that you can easily convert into a Timestamp.

Upvotes: 1

mplungjan
mplungjan

Reputation: 178385

You need to do

var dateIdOne = new Date(sessionStorage.getItem("dateOne"));
var dateIdTwo = new Date(sessionStorage.getItem("dateTwo"));

because

sessionStorage.setItem("dateOne", data.dateOne); 

converts date to toString()

and

fromDate is a static method from the static Timestamp class from Firebase. If you want to store a field as a timestamp in Firestore, you'll have to send a JavaScript Date object or a Firestore Timestamp object as the value of the field

Upvotes: 2

Related Questions