Florian K
Florian K

Reputation: 2148

Query a Map containing an ID saved in Cloud Firestore with Dart/Flutter

How to get a Map stored in Cloud Firestore with Dart/Flutter ? I tried this but it only works with Array :

Firestore.instance
            .collection('posts')
            .orderBy('createdAt', descending: true)
            .where("userlist", arrayContains: userId)
            .snapshots(),

here is the map stored in firebase

enter image description here

Upvotes: 1

Views: 3880

Answers (4)

emreoktem
emreoktem

Reputation: 2547

I've tried both Doug Stevenson's and Dan James's answers and was getting empty array as a result.

I've finally received the correct result by using the where clause with not equal to ''

Upvotes: 3

Mithun Kartick
Mithun Kartick

Reputation: 11

I don't recommend your way of data model. Because of some limitations as below:

  1. You can only have 20000 fields in a firestore document (including array fields).
  2. You can't assign security rules to each field. Security Rules is a thing that you have to think of.
  3. You can't query them.

So, better I would recommend you to use documents for each user.

Upvotes: 0

Dan James
Dan James

Reputation: 579

Just adding to Doug Stevenson's answer, I had to use the key isGreaterThan: '' in order to not get an empty array.

Firestore.instance
    .collection('posts')
    .where('userlist.' + userId, isGreaterThan: '')
    .snapshots(),

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317808

It doesn't really make sense for userlist to be an array here. Firestore doesn't let you query for values of maps inside an array. Just store it as a map. If userlist was just a map of uid/value pairs, you could query it like this using dot notation:

Firestore.instance
        .collection('posts')
        .orderBy('createdAt', descending: true)
        .where('userlist.' + userId, isEqualTo: true)
        .snapshots(),

Upvotes: 7

Related Questions