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

查看:48
本文介绍了如何在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天全站免登陆