Firestore或查询 [英] Firestore OR query

查看:49
本文介绍了Firestore或查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我在Firestore中有一个具有以下格式对象的集合:

Imagine I have a collection in Firestore with objects of the following format:

{
  /* ... */
  ownerId: "id-1",
  memberIds: [
    "id-2",
    "id-3",
    "id-4"
  ]
}

如何查询Firestore中所有在 ownerId 字段 OR memberIds中包含字符串 id-1 的文档字段?

How can I query Firestore for all documents where the string id-1 is present in the ownerId field OR the memberIds field?

我只找到AND查询,就像这样:

I only found AND queries, like so:

return collection('whatever')
  .where('memberIds', 'array-contains', 'id-1')
  .where('ownerId', '==', 'id-1');

但是这些只会返回给我 both ownerId 字段和 memberIds 数组.

But those will only return me the documents where id-1 is included in both the ownerId field and the memberIds array.

我知道我可以执行多个查询并合并结果,但这会使分页和排序变得麻烦很多.

I understand that I could perform multiple queries and join the results, but that would make pagination and ordering too much of a hassle to implement.

推荐答案

在Firestore中无法执行您所描述的OR查询.

It's not possible in Firestore to execute an OR query like the one you describe.

一种解决方案是对数据进行非规范化(这是NoSQL世界中非常普遍的方法),并向文档中添加一个额外的字段,该字段连接"到数据库.其他两个字段,如下所示:

One solution is to denormalize your data (a very common approach in the NoSQL world) and add, to the document, an extra field which "concatenates" the two other fields, as follows:

{
  /* ... */
  ownerId: "id-1",
  memberIds: [
    "id-2",
    "id-3",
    "id-4"
  ],
  ownersAndMemberIds: [
    "id-1", 
    "id-2",
    "id-3",
    "id-4"
  ]
}

然后,您可以轻松地通过以下方式查询文档

Then you can easily query the doc with

return collection('whatever')
  .where('ownersAndMemberIds', 'array-contains', 'id-1');


当然,您需要将此数组与其他字段保持对齐,但这并不困难.您可以在更新两个主"服务器之一时从前端进行操作.字段,或通过对文档进行任何更改都会触发的Cloud Function.


Of course it requires that you maintain this array aligned with the other fields, but this is not difficult. Either you do it from your front-end when you update one of the two "main" fields, or through a Cloud Function which is triggered on any change to the doc.

这篇关于Firestore或查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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