最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how do i retrieve the most recent document added to a collection? - Stack Overflow

programmeradmin1浏览0评论

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()
发布评论

评论列表(0)

  1. 暂无评论