获取 Firebase Firestore 集合中最后创建的文档 [英] Get last created document in a Firebase Firestore collection

查看:20
本文介绍了获取 Firebase Firestore 集合中最后创建的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Firebase Firestore 集合中获取上次创建的文档?我的要求是当用户签名时,我必须在名为history"的集合中添加一个文档;当用户退出时,我想使用名为退出"的字段更新该文档;因此,如果我获得最后添加的文档,则很容易更新.有没有办法做到这一点?

Is there any way to get last created document in Firebase Firestore collection? My requirement is when user signed I have to add a document in a collection named 'history'; When the user signed out I want to update that document with a field called 'signout'; So if i get the lastly added document it is very easy to update. Is there any way to do this?

推荐答案

有没有办法在 Firebase Firestore 集合中获取最后创建的文档?

Is there any way to get the last created document in Firebase Firestore collection?

是的,有!实现这一点的最简单方法是为集合中的每个对象添加一个 date 属性,然后简单地根据这个新属性 descending 查询它并调用 limit(1) 函数.就这样!

Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

正如@eyyo 在他的评论中提到的,这是一个具体的例子.假设您的数据库架构如下所示:

As @eyyo mentioned in his comment, here is a concrete example. Assuming that your database schema looks like this:

Firestore-root
  |
  --- history (collection)
        |
        --- docId (document)
             |
             --- date: June 24, 2020 at 6:46:25 PM UTC+3
             |
             --- //Other properties

这是必需的查询:

this.historyRef = afs.collection<History>('history', ref => ref.orderBy('date', 'desc').limit(1));
this.history = this.historyRef.snapshotChanges().map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as Hisotory;
        const docId = a.payload.doc.id;
        return { docId, ...data };
    });
});

这篇关于获取 Firebase Firestore 集合中最后创建的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆