获取按文件ID在Firestore中降序排列的数据 [英] Get data ordered by document Id descending in Firestore

查看:62
本文介绍了获取按文件ID在Firestore中降序排列的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的Firestore数据库中获取数据,该数据由documentId降序排列.当我打电话时:

I want to get data from my Firestore db ordered by documentId in descending order. When I call:

firestore.collection("users")
    .orderBy(FieldPath.documentId(), Query.Direction.DESCENDING)
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {...});

我遇到错误:

FAILED_PRECONDITION:查询需要索引.

FAILED_PRECONDITION: The query requires an index.

带有指向Firebase控制台的链接,用于自动创建索引.不幸的是,在这种情况下,自动创建似乎不起作用.当我单击创建索引"时,我收到一条消息:

With a link to Firebase console for automatic index creation. Unfortunately the automatic creation doesn't seem to work in this case. When I click on Create Index I get a message:

__ name__仅索引不支持

__name__ only indexes are not supported

对于手动创建索引,文档只是说字段名称(不是documentId).有谁知道如何从documentId降序排列的Firestore中获取数据?

For manual index creation, the doc only says about indexing by field name (not documentId). Does anyone know how to get data from Firestore ordered by documentId in descending order?

我知道我可以在客户端重新排序数据,但是按ID排序是很自然的任务,我肯定会丢失一些东西.谢谢你.我使用:

I know I can re-order data on client side, but ordering by id is such a natural task that I must be missing something. Thank you. I use:

compile 'com.google.firebase:firebase-firestore:11.6.0'

推荐答案

如Firestore文档此处,Cloud Firestore不提供对自动生成的docID的自动排序.

As stated in the Firestore document here, Cloud Firestore does not provide automatic ordering on the auto-generated docIDs.

重要:与Firebase实时数据库中的推送ID"不同,Cloud Firestore自动生成的ID不提供任何自动排序.如果希望能够按创建日期排序文档,则应将时间戳记存储为文档中的字段.

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

因此,您可以通过添加额外的字段 createdDate 并将其设置为

Hence you can achieve ordering by adding an extra field createdDate and just setting it with annotation @ServerTimestamp, declaring it before the class field in your user POJO like this.

@ServerTimestamp
Date createdDate;

此外,当在Firestore上写POJO时,必须确保此字段为空,在将其保存到Firestore之前,请勿对其设置任何值.

Also you must ensure this field is null when the POJO is being written on Firestore, do not set any value to it before saving it on Firestore.

这篇关于获取按文件ID在Firestore中降序排列的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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