如何在Flutter中使用查询访问Cloud Firestore的数组索引? [英] How to access array index of Cloud Firestore using query in Flutter?

查看:157
本文介绍了如何在Flutter中使用查询访问Cloud Firestore的数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中有字段users,该字段在数组中包含两个元素.我必须检查特定的两个值在此数组中.

I have field users in document and this field contains two element in array. I have to check specific two values are in this array.

首先,我为此使用了两次array-contains方法,但是发生了错误.

First, I used array-contains method twice for this, but it occurred error.

如何在Cloud Firestore中访问数组字段的索引?

How can I access index of array field in Cloud Firestore?

下面的代码是我的方法,它不起作用:

Below code is my approach and it is not working:

QuerySnapshot querySnapshot = await sl.get<FirebaseAPI>().getFirestore()
      .collection('messages')
      .where('users'[0],isEqualTo: 'user1ID')
      .where('users'[1],isEqualTo: 'user2ID')
      .getDocuments();

简单的Firestore结构

推荐答案

Firestore无法使用其中的Firestore来基于数组中存在的元素的索引来查询数据库.的确,您不能在一个查询中链接多个array-contains调用,但是还有另一种解决方法可以帮助您实现同一目标.因此,您的数据库结构需要进行更改.因此,可以使用映射而不是使用数组,而您的架构应类似于以下内容:

There is no way Firestore in which you can query the database based on an index of an element that exist within an array. It's true that you cannot chain more than one array-contains calls in a query but there is another workaround that can help you achieve the same thing. So a change is needed in your database structure. So instead of using an array you can use a map and your schema should look similar to this:

Firestore-root
   |
   --- messages (collection)
         |
         --- users (map)
              |
              --- user1ID: true
              |
              --- user2ID: true

现在这样的查询将可以正常工作:

Now a query like this will work perfectly fine:

QuerySnapshot querySnapshot = await sl.get<FirebaseAPI>().getFirestore()
    .collection('messages')
    .where('users.user1ID',isEqualTo: true)
    .where('users.user2ID',isEqualTo: true)
    .getDocuments();

这篇关于如何在Flutter中使用查询访问Cloud Firestore的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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