简体   繁体   中英

How to get last element of document in firestore?

db.collection("todolist").get().then((querySnapshot) => {
console.log(querySnapshot[querySnapshot.length -1])})

This results in undefined. How do i get the last element of a document?

querySnapshot isn't an array, so you can simply index into it. It's a QuerySnapshot object, and I strongly suggest you familiarize yourself with that API documentation. You can see that it has a docs property, which is an array.

querySnapshot.docs[querySnapshot.docs.length-1]

or

querySnapshot.docs[querySnapshot.size-1]

If you're only interested in the last document, consider ordering the query, and requesting only one document, so save on the bandwidth and cost. Say you have a field named timestamp , you can get the latest one (and only that one) with:

db.collection("todolist")
  .orderBy("timestamp", "desc")
  .limit(1)
  .get().then((querySnapshot) => {
    console.log(querySnapshot.docs[0])
  })

Since you now only requested one document, you can use docs[0] to get at it.

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