gpt4 book ai didi

javascript - 如何检索添加到集合中的最新文档?

转载 作者:行者123 更新时间:2023-12-01 00:17:25 26 4
gpt4 key购买 nike

使用cloud-firestore存储用户计算器中的一些数据,而不是获取集合中的所有文档,我怎样才能获取最新的文档?

当前设置是:

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

最佳答案

Firestore 没有“最新文档”的内部概念。 Firestore 应用于文档的唯一顺序是您使用添加到文档的字段定义的顺序。

如果您想要新近度的概念,您应该使用 server timestamp 包含时间戳类型字段。将集合中的每个文档添加到集合中时,将其添加到集合中,然后使用该字段查询该文档。然后你可以用它 order and limit documents .

如果您的文档中有一个名为“timestamp”的时间戳类型字段,这将为您提供最新的字段:

db.collection("calculations")
.orderBy("timestamp", "desc")
.limit(1)
.get()

关于javascript - 如何检索添加到集合中的最新文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59671657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com