admin管理员组

文章数量:1406945

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;
     });
 });

image of database here

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;
     });
 });

image of database here

Share Improve this question asked Jan 9, 2020 at 20:31 sisternight438sisternight438 1531 gold badge3 silver badges14 bronze badges 1
  • Here is a great tutorial: link – radulle Commented Jan 9, 2020 at 23:42
Add a ment  | 

1 Answer 1

Reset to default 8

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()

本文标签: javascripthow do i retrieve the most recent document added to a collectionStack Overflow