Home > OS >  How to retrieve documents in firestore order with timestamp with React
How to retrieve documents in firestore order with timestamp with React

Time:02-25

I wrote the following code.

const salons = query(collection(db, "user"), orderBy('', "desc"), limit(5))
const querySnapshot = await getDocs(salons)
await querySnapshot.forEach((doc) => {
    console.log(new Date(doc._document.version.timestamp.seconds * 1000).toString())
    //processing
})

I want to sort the orderby by "doc._document.version.timestamp.seconds" which is displayed in console.log.

But I don't know how to do it. This date is automatically registered by firestore, so the position of the value is different. Does anyone know how I can sort it?

CodePudding user response:

Firestore can only order/filter data on values that it has indexes for. Indexes are only created for fields in your document (and the document ID), not for implicit metadata such as the timestamp it keeps internally.

There is no way to order Firestore results based on the internal timestamp. If you want to be able to order documents on a timestamp, you'll have to store that timestamp as a field in the document, and then pass that field name to orderBy.

  • Related