简体   繁体   中英

Get the 10 last documents from firestore

I'm trying to get the last ten documents created on firestore. I tried everything, for example:

firebase.firestore()
    .collection("posts")
    .where("createdAt", "<=", new Date().getTime())
    .limit(10)

or

firebase.firestore()
    .collection("posts")
    .orderBy("createdAt")
    .limit(10)

but instead of returning the last 10, it returned the first 10. Then I tried

firebase.firestore()
    .collection("posts")
    .limit(10)

and it worked fine for the first eleven documents, but when I passed that quantity of documents it started skipping some documents.

First, you need to define a sort order for your query. If you want the last 10 documents in that order, you should then reverse the sort order. If you want the last 10 sorted by the field createdAt , then you should define a sort order like this:

firebase.firestore()
    .collection("posts")
    .orderBy("createdAt", "desc")
    .limit(10)

"desc" will reverse the default sort order, making them sort from greatest to lowest.

I suggest reviewing the documentation on ordering and limiting data to learn more.

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