Listen to updates on certain query with array fiel

2019-08-18 17:24发布

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 = ");
                    });

enter image description here

1条回答
戒情不戒烟
2楼-- · 2019-08-18 17:57

Edit: September 12, 2018

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


As in the official documentation regarding arrays:

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

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());
    }
}

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

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
}
查看更多
登录 后发表回答