Home > Back-end >  Adding dynamic where conditions to a firebase query
Adding dynamic where conditions to a firebase query

Time:03-26

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

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.

CodePudding user response:

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();
  • Related