1

I have a ProductDatabase collection which stores all the products I'm displaying on my app. Each document in the collection has a timestamp field called 'SBD' which represents the sell by date of each item. I have created and uploaded a cloud function which checks the each item in the database every 2 hours to check that every items SBD field has not passed. This is the function:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

exports.delete = functions
    .region("europe-west2")
    .pubsub.schedule("every 2 hours").onRun((context) => {
      const productsRef = admin.firestore().collection("TestDatabase");

      const query = productsRef.where("SBD", "<", Date.now());

      return query.get()
          .then((querySnapshot) => {
            const batch = admin.firestore().batch();

            querySnapshot.forEach((doc) => {
              batch.delete(doc.ref);
            });

            return batch.commit();
          });
    });

This program uploads appears in the firebase cloud functions console and says it's being invoked every 2 hours however no products are deleted from the TestDatabase even though they should all be deleted. The index.js file is stored in a bucket in the google cloud console which has all the necessary permissions. The database and cloud function are also in the same region.

ReDue
  • 25
  • 3

1 Answers1

0

The problem is that you're doing an invalid comparison on the SBD field. If SBD is a Timestamp object then your query must use a Timestamp object in the comparison.

This is an invalid comparison and will always return 0 records because you cannot compare two different object types:

const query = productsRef.where("SBD", "<", Date.now());

This is a valid comparison performed by getting UNIX time and converting it to a Timestamp:

const seconds = Math.floor(Date.now() / 1000)
const nanoseconds = 0
const now = new Timestamp(seconds, nanoseconds)
const query = productsRef.where("SBD", "<", now);

You can read more at How to compare firebase timestamps?.

anothermh
  • 9,815
  • 3
  • 33
  • 52
  • 2
    `Date.now()` doesn't even return a Date object. [It returns a number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now). Firestore can actually automatically convert a Date for use with Timestamp with no problems, but it can't convert a number to compare with a timestamp. – Doug Stevenson Apr 07 '23 at 02:08
  • thanks for both of your answers I managed to fix the problem by defining the current time as: ```const now = admin.firestore.Timestamp.now();``` – ReDue Apr 07 '23 at 14:22