如何获取 Firebase Cloud Firestore 中存在/不存在特定字段的文档? [英] How do I get documents where a specific field exists/does not exists in Firebase Cloud Firestore?

查看:25
本文介绍了如何获取 Firebase Cloud Firestore 中存在/不存在特定字段的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Firebase Cloud Firestore 中,我的集合中有user_goals",目标可能是预定义的目标(master_id:XXXX")或自定义目标(无master_id"键)

In Firebase Cloud Firestore, I have "user_goals" in collections and goals may be a predefined goal (master_id: "XXXX") or a custom goal (no "master_id" key)

在 JavaScript 中,我需要编写两个函数,一个获取所有预定义目标,另一个获取所有自定义目标.

In JavaScript, I need to write two functions, one to get all predefined goals and other to get all custom goals.

我有一些解决方法来通过将master_id"设置为"空字符串来获得自定义目标,并且能够获得如下:

I have got some workaround to get custom goals by setting "master_id" as "" empty string and able to get as below:

db.collection('user_goals')
    .where('challenge_id', '==', '')  // workaround works
    .get()

这仍然不是正确的方法,我继续将其用于预定义的目标,其中具有如下所示的master_id"

Still this is not the correct way, I continued to use this for predefined goals where it has a "master_id" as below

db.collection('user_goals')
    .where('challenge_id', '<', '')  // this workaround
    .where('challenge_id', '>', '')  // is not working
    .get()

由于 Firestore 没有!="操作符,我需要使用<"和 ">" 运算符,但仍然没有成功.

Since Firestore has no "!=" operator, I need to use "<" and ">" operator but still no success.

问题:忽略这些变通方法,通过检查特定字段是否存在来获取文档的首选方法是什么?

推荐答案

作为@Emile Moureau 解决方案.我更喜欢

As @Emile Moureau solution. I prefer

.orderBy(`field`)

要查询具有该字段的文档.因为它可以处理具有任何值的任何类型的数据,即使对于 null.

To query documents with the field exists. Since it will work with any type of data with any value even for null.

但正如@Doug Stevenson 所说:

But as @Doug Stevenson said:

您无法查询 Firestore 中不存在的内容.一个字段需要存在才能让 Firestore 索引知道它.

You can't query for something that doesn't exist in Firestore. A field needs to exist in order for a Firestore index to be aware of it.

如果没有该字段,您将无法查询文档.至少现在是这样.

You can't query for documents without the field. At least for now.

这篇关于如何获取 Firebase Cloud Firestore 中存在/不存在特定字段的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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