如何查询Cloud Firestore中不存在的文档密钥 [英] How to query Cloud Firestore for non-existing keys of documents

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

问题描述

假设我有一个带有一些可选属性的数据模型.例如,这可以是具有名字",姓氏"和可选网站"属性的用户对象.

Let's say I have a data model with some optional properties. This could be for example a user object with a "firstname", a "lastname" and an optional "website" property.

在Cloud Firestore中,只有具有已知网站的用户文档才会设置网站"属性,对于所有其他用户文档,此属性将不存在.

In Cloud Firestore only user documents with a known website would have the "website" property set, for all other user documents this property would not exist.

我现在的问题是如何没有网站"属性的情况下查询所有用户文档.

My questions is now how to query for all user documents without a "website" property.

谢谢.

推荐答案

文档可以包含具有null值数据类型的属性(请参见

Documents can contain properties with a null value data type (see data types documentation). This will then allow you to construct a query to limit results where the website property is null.

这与缺少的属性不太一样,但是如果您使用

This is not quite the same as a missing property, but if you use custom objects to write data to Firestore, empty properties will automatically be saved as null rather than not at all. You can also manually/programmatically write a null value to the database.

在Android中,我使用以下工具对此进行了测试:

In Android, I tested this using the following:

FirebaseFirestore.getInstance().collection("test").whereEqualTo("website", null).get();

我的数据库结构如下:

这仅返回文档inuwlZOvZNTHuBakS6GV,因为文档9Hf7uwORiiToOKz6zcsXwebsite属性中包含字符串值.

This returned only the document inuwlZOvZNTHuBakS6GV, because document 9Hf7uwORiiToOKz6zcsX contains a string value in the website property.

我相信您通常在Swift中开发,不幸的是,不支持自定义对象,但是您可以使用NSNull()null值写入Firestore.例如(我不精通Swift,所以可以随时纠正任何问题)

I believe you usually develop in Swift, where unfortunately custom objects aren't supported, but you can use NSNull() to write a null value to Firestore. For example (I'm not proficient in Swift, so feel free to correct any issues):

// Writing data
let docData: [String: Any] = [
    "firstname": "Example",
    "lastname": "User",
    "website": NSNull()
]
db.collection("data").document("one").setData(docData) { err in
    if let err = err {
        print("Error writing document: \(err)")
    } else {
        print("Document successfully written!")
    }
}

// Querying for null values
let query = db.collection("test").whereField("website", isEqualTo: NSNull())

文档中没有提到查询不存在的值的方法,因此这似乎是下一个最佳方法.如果有人可以改善或提出替代方案,请这样做.

The documentation doesn't mention a method to query for values that don't exist, so this seems like the next best approach. If anyone can improve or suggest alternatives, please do.

这篇关于如何查询Cloud Firestore中不存在的文档密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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