Evan
Evan

Reputation: 880

Increment date and batch create Firestore documents

I have a map of data:

{
    name: name,
    time: <epoch in seconds>,
}

My goal is to create 6 documents with this data in Firestore, but with each document, the time field should be incremented by 1 week. So if my initial time is Sun Nov 17 2019 in epoch, there should be 6 documents with time (as Firestore timestamp) Sun Nov 17 2019, Sun Nov 24 2019, Sun Dec 1 2019, etc.

I'm using a https cloud function and tried doing this:

var name = 'test';
var time = 1573992000; // 7 AM EST on Sun, Nov 17 2019
var data = {
    name: name,
    time: time,
};

var start = new Date(time * 1000); // convert to milliseconds

var i;
for (i = 0; i < 6; i++) {
    var ref = db.collection('shifts').doc();

    start.setDate(new Date(start) + 7);

    data['time'] = new admin.firestore.Timestamp(start.getTime() / 1000, 0);

    batch.set(ref, data);
}

return batch.commit();

But all the documents appear in firestore with the same time (6 weeks after the initial). My guess is that it's something with the batch only setting the latest value. How can I avoid this without having to create 6 separate maps?

Upvotes: 1

Views: 240

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

You usage of Date looks overall incorrect to me.

setDate() sets the date of the month to the exact value, and it will not increment the month if needed to accommadate values that go beyond what the month allows (that is to say, if you pass 32, no month would ever accept that).

Also this doesn't make sense to me: new Date(start) + 7. You can't simply add 7 to a date object. It looks like maybe you meant to add 7 to the date of the month represented in the date. But again, that won't work the way you expect if the value is too high for the given month.

All things considered, the Date object isn't going to help you out too much here. I suggest just doing date math on integer numbers. For example, if your start time is:

var time = 1573992000

You can add 7 days worth of seconds to it like this:

time + (7 * 24 * 60 * 60)

This should be easier to work with.

Upvotes: 1

Related Questions