1

i have a generic model for get all items from Schema .

export interface FilterViewModel<T> {
    filters: T
}

now i use that by this model :

GetAllUsersPaging(items: FilterViewModel<GetAllUserFilter>)

and this is items of my models :

   export interface GetAllUserFilter {
    blocked: boolean,
    emailConfirmed: boolean,
    isActive: boolean,
    isDeleted: boolean,
    personalVerified: boolean,
    phoneNumberConfirmed: boolean,
    phoneNumber: string
}

now i want to search in all filters item and push that in the variable . i write this code but it not worked and not go loop in the all items and just once loop .

    async GetAllUsersPaging(items: FilterViewModel<GetAllUserFilter>) {

    let query: any = [];


    [items.filters].forEach((element) => {

        if (!element.phoneNumber) {
            query.push(element);
        } else {
            query.push({ phoneNumber: { $regex: `(.*)${element.phoneNumber}(.*)` } });
        }

    });

}

now whats the problem ? how can i loop in all items in items.filters ???

1 Answer 1

1

items.filters looks like an object instead of an array, and I think your idea is loop thought all key of GetAllUserFilter and append them, their value to query array.

You can use Object.keys to get all keys of an object, then loop thought them to check their name and value object the object at the key.

async GetAllUsersPaging(items: FilterViewModel<GetAllUserFilter>) {

  const query: any = [];

  Object.keys(items.filters).forEach(key  => {
    const value = items.filters[key as keyof GetAllUserFilter];
    if (key === 'phoneNumber' && value) {
      query.push({ phoneNumber: { $regex: `(.*)${value}(.*)` } });
    } else {
      query.push({ [key]: value }); // ex: { blocked: true }
    }
  });
}
2
  • when i use your code it show me this error : MongoError: Unsupported projection option: phoneNumber: { $regex: "(.*)0914(.*)" } Jan 31, 2021 at 6:51
  • query.push({ phoneNumber: { $regex: new Regex(value) });
    – hoangdv
    Jan 31, 2021 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.