Home > Back-end >  Javascript convert array to object to use in Find in Mongoose
Javascript convert array to object to use in Find in Mongoose

Time:07-25

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?

CodePudding user response:

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);

CodePudding user response:

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