Home > other >  How to get last element of document in firestore?
How to get last element of document in firestore?

Time:01-24

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?

CodePudding user response:

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]

CodePudding user response:

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.

  •  Tags:  
  • Related