Reputation: 11
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?
Upvotes: 1
Views: 2252
Reputation: 598765
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.
Upvotes: 3
Reputation: 317402
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]
Upvotes: 1