0

I'm trying to do a dynamic filter building for a search in Mongoose.

I got an array containing various filters, and I would like to use them in this.mySchema.find ({QUERY}) as follows:

[
  { name: { '$eq': 'John' } },
  { surname: { '$regex': '.*t', '$options': 'i' } }
]

Now I would like to search by all filters as below

const query = this.customerModel.find(findFilters);

But I am getting the error below

Parameter "filter" to find() must be an object, got [object Object],[object Object]

I tried converting this to an object, but I'm getting something that I can't use either

{ ...findFilters }

Result:

{
  '0': { name: { '$eq': 'John' } },
  '1': { surname: { '$regex': '.*t', '$options': 'i' } }
}

I also tried this:

const result = {};
findFilters.forEach(e => result[e] = {});

But I got something that also doesn't work in Find and the filters don't work during the search

{ '[object Object]': {} }

So, how can I use my array of filters in the Find method?

2 Answers 2

2

You need to reduce() to a single object:

const filters = [
  { name: { '$eq': 'John' } },
  { surname: { '$regex': '.*t', '$options': 'i' } }
];

const filter = filters.reduce((a, v) => ({...a, ...v}), {});

console.log(filter);

Sign up to request clarification or add additional context in comments.

1 Comment

I used your help to answer my own question in another thread and to share my solution. stackoverflow.com/questions/73101686/…
0

Your result is an pending promise

you need to use an async function and use await:

const query = await this.customerModel.find(findFilters);

Or .then()

this.customerModel.find(findFilters).then(res => {
   console.log(res);
})

4 Comments

I have the await in the next line return await query.exec();
@g_m you dont posted it
True, since I was focused on the Find and filtering, but yes you are right regarding to the mongoose and the async/await. Thank you
I put the (almost) complete code in answer to my own question in this thread: stackoverflow.com/questions/73101686/… I will be glad if you have any suggestions for my solution that I shared there...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.