聆听Cloud Firestore(Android)上具有数组字段的某些查询的更新 [英] Listen to updates on certain query with array fields on Cloud Firestore (Android)

查看:54
本文介绍了聆听Cloud Firestore(Android)上具有数组字段的某些查询的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下图显示了简单聊天应用程序的数据结构.当两个用户想要通信时,会在他们之间创建一个频道.成员字符串数组字段列出了用户名.

The picture below shows the data structure for the simple chat application. A channel is created between two users when they want to communicate. Member string array field lists the usernames.

我想在登录用户的任何渠道收到消息时通知用户.不确定如何做到这一点.

I want to notify the user when any of the channels of logged in user receive a message. Not sure how this can be done.

我尝试了以下查询,但均未成功.有任何想法吗?

I tried below query with no success. Any ideas?

    listenerRegistration2 =
            firebaseFirestore.collection(COLLECTION_CHANNELS)
                    .whereEqualTo("members.0", username)
                    .addSnapshotListener((queryDocumentSnapshots, e) -> {
                        Log.d("myApp", "queryDocumentSnapshots = ");
                    });

推荐答案

2018年9月12日

August 28, 2018开始,现在可以更新数组成员.更多信息 此处

Starting with August 28, 2018, now it's possible to update array members. More informations here.

与有关数组的官方文档中一样:

As in the official documentation regarding arrays:

尽管Cloud Firestore可以存储阵列,但 it does not support 可以查询阵列成员或更新单个阵列元素.

Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.

因此,不幸的是,您无法使用数组来实现此目的.如果只想获取整个memebers数组,则只需使用get()调用,然后仅对Map进行迭代,如下所示:

So unfortunately you cannot achieve this using arrays. If you only want to get the entire memebers array, just use a get() call and then only to iterate over a Map like this:

Map<String, Object> map = documentSnapshot.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (entry.getKey().equals("memebers")) {
        Log.d("TAG", entry.getValue().toString());
    }
}

但是请注意,即使memebers对象作为数组存储在数据库中,entry.getValue()也会返回ArrayList,而不是array.

But note, even if memebers object is stored in the database as an array, entry.getValue() returns an ArrayList, not an array.

这里还有一个解决方法,可以帮助您实现此目标,但是您需要将memebers数组属性更改为map.因此,一种更好的方法是考虑这种替代的数据库结构,其中每个成员都是映射中的键,并且所有值都是真实的:

There is also an workaround here, that can help you achieve this but you need to change the memebers array property to a map. So a better approach will be if you consider this alternative database structure, where each memeber is the key in a map and all values are true:

memebers: {
    "sister12": true,
    "wow": true
}

这篇关于聆听Cloud Firestore(Android)上具有数组字段的某些查询的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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