Dan Briggs
Dan Briggs

Reputation: 63

Firestore how to make new timestamp field and how to query with dates?

exports.resetDailyFinalKills = functions.pubsub
    .schedule("*/5 * * * *")
    .timeZone("Europe/Berlin")
    .onRun(async (context) => {
      const players = firestore.collection("players");
      const goodtimes = await players
          .where("registerDate", "<=", Date.now()-84600)
          .get();
      goodtimes.docs.forEach((snapshot) => {
        const uuid = snapshot.data().uuid;
        const url = `https://api.hypixel.net/player?key=x&uuid=${uuid}`;
        const settings = {method: "Get"};

        fetch(url, settings)
            .then((res) => res.json())
            .then((data) => {
              const finals = data.player.stats.Bedwars.final_kills_bedwars;
              const date = snapshot.data().registerDate;
              snapshot.ref.update({todayFinalKills: finals});
              snapshot.ref.update({registerDate: firebase.firestore
                  .Timestamp.fromDate(new Date(date+84600))});
              console.log("got in");
              console.log(finals);
            });
        //  snapshot.ref.update({final_kills: 0});
      });
      return null;
    });

So I have this function, first problem is

snapshot.ref.update({registerDate: firebase.firestore
                      .Timestamp.fromDate(new Date(date+84600))});

I'm trying to add a new timestamp to the registerDate field but it's not working? Second .where("registerDate", "<=", Date.now()-84600) here I'm trying to look for dates older than 24 hours but this also isn't working because I guess date's arent simply stored as numbers but I'm not sure how I would do what I want to here?

Upvotes: 0

Views: 238

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Timestamps are not stored as numbers. A query that uses a number for a filter will never match a timestamp, like you are doing here:

const goodtimes = await players
          .where("registerDate", "<=", Date.now()-84600)
          .get();

That query will only match documents where registerDate is a number within the requested range.

If you want to match document fields with a timestamp, you have to use a Timestamp object in the query filter A Date will work as well.

const goodtimes = await players
          .where("registerDate", "<=", new Date(Date.now()-84600))
          .get();

Upvotes: 1

Related Questions