[英]Retrieve newest 2 documents from a collection
我需要从 google cloud firestore 的集合中检索前 2 个文档。 我想到的方法是我有最新文档的时间戳,然后减去第一个和最后一个之间的毫秒数,然后检索该范围。
let firstStamp: number = [example timestamp in ms]
const query: any = await admin.firestore().collection('collection').where('timestamp', '<', firstStamp);
let documents: any;
query.where('timestamp', '>', firstStamp - 15000);
return query.get().then(result => {
if (result.size === 0) {
log(`No data. If this happens i've done something wrong with my query.`);
return;
};
documents = result.docs;
});
我没有收到错误消息没有日志,但这不起作用。 任何人都可以看到有什么问题吗?
如果有更好的方法来做到这一点,请告诉我。
如果您在每个文档中都有一个与其创建相对应的timestamp
字段,您可以非常轻松地查询最近的两个,如下所示:
import { collection, query, orderBy, limit, getDocs } from "firebase/firestore";
const q = query(collection(db, "collection"), orderBy("timestamp", "desc"), limit(2));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.