Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding dynamic where conditions to a firebase query

I am currently trying to fetch data in my firestore data base via document properties,

I discovered that I can do it this way

const qsnap = await firebase.firestore()
    .collection('blog-posts')
    .where(firebase.firestore.FieldPath.documentId(), "==", id)
    .where("published", "==" true)
    .get()

I’m trying to make it smarter or more dynamic

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This works perfectly but I found a problem and it is that I wanted to assign the where conditions to the query dynamically
in order to pass through a map the properties that I want to look for, something like this

params.forEach((k, v) => {
    _mainCollection.where(k, isEqualTo: v)
});
var result = await _mainCollection.get();

I thought this would work since I’m assigning several wheres for each value inside a map but it doesn’t seem to work I’m not sure why

then try this

Query? query;
params.forEach((k, v) => {
   query = _mainCollection.where(k, isEqualTo: v)
});
var result = await query!.get();

And it works but as you could imagine it is only assigning the last value of the map to the query since I am always overwriting it

So I’m looking for a way to contain several where conditions within the query, basically all the conditions that are stored in the foreach map or if there is any way to dynamically add them to the collection query it would be great, if someone knows how to do the trick for me It would help a lot.

>Solution :

You’re almost there. Since Query is the parent class of Collection, you can do:

Query query = _mainCollection;
params.forEach((k, v) => {
   query = query.where(k, isEqualTo: v)
});
var result = await query!.get();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading