Search code examples
node.jsfirebasegoogle-cloud-firestoretimestamp

Get documents from firestore based on timestamp field


I am trying to get all the documents with a dateStart timestamp field that is less than 24 hours in the future using a collectionGroup query. However, it would not be ideal to get all documents and test it for each document, as the documents can accumulate over time.

I have tried to do the following, but it gives an error:

const currentDate = moment();
const snap = db.collectionGroup('appointments').where(moment.duration(currentDate.diff(moment(new Date('dateStart')))).asHours() < 25).get()
  .then(function(querySnapshot){
    querySnapshot.forEach(function(doc){
      console.log(doc.id);
    });
  });

The error I am getting is the following:

Error: Value for argument "fieldPath" is not a valid field path. Paths can only be specified as strings or via a FieldPath object.

I am not sure if it is even possible to add logic like this in the where clause of the query, or if I am just doing this the wrong way. I am currently using the moment library, but this isn't mandatory for the solution. I do think it is the easiest way to get the difference between date objects.

Does anyone have an idea to get this done without looping through all the documents in the collection?


Solution

  • You are doing something very weird.

    The where function should be:

    .where('dateStart', '<', next24HoursDate)
    

    So try something like this:

        const next24HoursDate = moment(new Date()).add(24, 'hours');
        
        const snap = db.collectionGroup('appointments')
          .where('dateStart', '<', next24HoursDate)
          .get()
          .then( function(querySnapshot) {
            querySnapshot.forEach( function(doc) {
            console.log(doc.id);
          });
        });