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

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

问题描述

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

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'));
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天全站免登陆