Theo
Theo

Reputation: 122

Querying Firestore map fields in flutter

I am trying to retrieve posts in my Firestore database from a field called "bookmarks". The field "bookmarks" is of type map. When a user bookmarks a post, the field is updated with the deviceId being set to true like this:

▼ bookmarks
     deviceId : true

When the post is unbookmarked, deviceId : trueis deleted and the bookmarks field remains empty like this:

bookmarks: {}

I am trying to retrieve posts from "bookmarks" where deviceID is set to true. My query however returns all posts including posts where bookmarks is empty.

This is my query :

QuerySnapshot snapshot = await postsRef
        .document(postId)
        .collection('users_posts')
        .where('bookmarks', arrayContains: deviceId)
        .orderBy('timestamp', descending: true)
        .getDocuments();

Please help figure out what I am doing wrong. Attatched is the structure of my database. Thank you.

enter image description here

enter image description here

Upvotes: 0

Views: 1623

Answers (2)

Camilo Quintero
Camilo Quintero

Reputation: 1

I tried that notation but didn't work for me, here is the notation I used: where("bookmarks.deviceId:true"), you can replace true with the value you are looking.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317808

Your bookmarks field is not an array, so you can't query it like an array. It's a map, and you can query for the values of nested fields of a map using dot notation:

.where('bookmarks.${deviceId}', isEqualTo: true)

Upvotes: 5

Related Questions