简体   繁体   中英

How to select documents in a firestore subcollection that are past a certain date?

I have the following subcollection merchants/id/bookings/date Here, 'bookings' is the subcollection and 'date' is the name of a document which contains bookings for that date. Here's an example: merchants/a9sd7f692934/bookings/25-07-2020

(1) in my 'where' function, how to define the name of the document?

(2) this involves dates and I am using moment for this. So how to transform a date that comes from firebase inside of the 'where' function?

I would like to get all of the documents that have a date > currentDate and here's what I'm trying but don't know how to proceed

//currentDate = 20-07-2020 //typeof String
           firebase
          .firestore()
          .collection('merchants')
          .doc(id)
          .collection('bookings')
          //??? -> how to get doc by its name? how to compare it to a moment date? how to convert it? 
          .where("???", ">", currentDate).get().then(docs => {
              console.log(docs.data())
            }
          })

I think you're looking for FieldPath.documentId : https://firebase.google.com/docs/reference/js/firebase.firestore.FieldPath#documentid

But the way you currently represent dates into the document ID does not lend itself for range operations. Say you want all documents in July, there's no way to filter 25-07-2020 on that.

You'll need to name your documents in most important to least important order, so: 2020-07-25 . Then you can query for:

firebase
  .firestore()
  .collection('merchants')
  .doc(id)
  .collection('bookings')
  .where(FieldPath.documentId(), ">", "2020-07-")
  .where(FieldPath.documentId(), "<=", "2020-07-31")
  .get().then(docs => {
     docs.forEach((doc) => {
       console.log(doc.data())
     });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM