how to properly perform query by date in Firestore

2019-08-06 09:30发布

I am trying to make a cronjob to delete an event that has been passed by using http trigger. today is 7th September, so the event at 5 september ( 6fqmROcWD7K1pTFtXmJJ )like the picture below shall be captured in the query snapshot. but the document length is zero

enter image description here

here is the code I use:

export const cronJobDeletingPastEvents = functions.https.onRequest(async (request,response) => {

        const dateNow = Date.now()
        const pastEventsSnapshot = await admin.firestore().collection("events").where('dateTimeFinish', '<', dateNow).get()
        console.log(pastEventsSnapshot.docs.length) // <---- the result is zero

// perform some actions ....

}

I don't know what went wrong in here, but I guess this is because dateNow is number, but the field dateTimeFinish in firestore is Timestamp object. but i dont know how to fix that

1条回答
Ridiculous、
2楼-- · 2019-08-06 10:14

The following will work:

const dateNow = new Date()

const pastEventsSnapshot = await admin.firestore().collection("events").where('dateTimeFinish', '<', dateNow).get()
...

The followings would also work:

const dateNow = new Date('2018-09-07T01:25:54.000Z')
const dateNow = new Date('2018-09-07')
查看更多
登录 后发表回答