Reputation: 153
using cloud-firestore to store some data from a user calculator, rather than getting all the documents in the collection, how can I just get the most recent?
current set up is:
db.collection("calculations")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log("doc", doc);
document.getElementById("final-results").innerText +=
"\n" + doc.data().calcuation;
});
});
Upvotes: 1
Views: 3428
Reputation: 317392
Firestore doesn't have an internal concept of "most recent document". The only ordering that Firestore applies to documents are the ones that you define using the fields you add to the document.
If you want a concept of recency, you should include a timestamp type field using a server timestamp to each document in the collection when you add it to the collection, then query that document using that field. Then you can use that to order and limit documents.
If you have a timestamp type field called "timestamp" in your documents, this will give you the most recent one:
db.collection("calculations")
.orderBy("timestamp", "desc")
.limit(1)
.get()
Upvotes: 7