Order by with where 不等式限制 Firestore

uks*_*ksz 6 javascript firebase google-cloud-firestore

假设我有以下简单的查询whereorderBylimit,这将返回我最近更新的公开个人资料(因此where)(因此orderBy)。

db.collection('profile')
   .where('public_profile', '==', true)
   .orderBy('updated_at', 'desc')
   .limit(1)
   .onSnapshot(function(doc) {
        ...
   });
Run Code Online (Sandbox Code Playgroud)

现在,我想添加一些额外的逻辑,这意味着我只想显示低于某种级别的配置文件。当我执行以下操作时:

db.collection('profile')
   .where('public_profile', '==', true)
   .orderBy('updated_at', 'desc')
   .where('level', '<=', 5)
   .limit(1)
   .onSnapshot(function(doc) {
        ...
   });
Run Code Online (Sandbox Code Playgroud)

我得到以下错误:

查询无效。您在字段 'talent.level' 上有一个带有不等式(lessThan、lessThanOrEqual、greaterThan 或 GreaterThanOrEqual)的 where 过滤器,因此您还必须使用 'level' 作为您的第一个 queryOrderedBy 字段,但您的第一个 queryOrderedBy 当前位于字段 'updated_at ' 反而。

据我了解,我需要添加额外的orderBy,给我以下内容:

db.collection('profile')
   .where('public_profile', '==', true)
   .where('level', '<=', 5)
   .orderBy('level', 'desc')
   .orderBy('updated_at', 'desc')
   .limit(1)
   .onSnapshot(function(doc) {
        ...
   });
Run Code Online (Sandbox Code Playgroud)

但是,这给我带来了错误的结果:它不会返回级别低于或等于 5 的最近更新的公开资料。它返回最高级别的资料中最近更新的公开资料.

大家有没有发现类似的问题?如果是,您的解决方案是什么?

小智 2

正如限制页面(单击)中的文档所述,如果您使用范围比较(<、<=、>、>=),您使用的第一个顺序应该是过滤的相同字段。

修复订单后,它可能会提示您创建该集合的广告​​索引以便使用这些条件。

提示:在 firestore 上,where 条件应位于顶部,order by 应位于底部。(这对于更好地理解条件订单很有用)