0

I'm trying to create a dynamic filter that can be implemented using at least 3 letters. I've got a lot of fields which i will be filtering against.

As an example, If I am trying to find users by email, I want to be able to type "@gma" or at least "gma" and ideally, it should return an array of all users containing the specified filtering value. This should be the same when searching for properties like firstName and so on

My current solution only works if I provide a full value that matches what I already have in my database. e.g [email protected] for email or john for firstName. I want to be able to type jo for the latter.

const regexPattern = new RegExp(["^", filterUsersByValue, "$"].join(""), "i");
const filteredU = UserModel.find({ [filterUsersBy]: regexPattern})
2
  • Do you want the key value to be dynamic too? The user gives you the key and value to regex and you create the query? Commented Oct 20, 2021 at 12:03
  • Yes i'd like that. Commented Oct 20, 2021 at 12:09

1 Answer 1

2

If I've understood correctly, since you are using JS you can create the find object like this:

let findObj = {}
findObj[userKey] = {$regex:userFilter, $options:"i"}
const filteredU = UserModel.find(findObj)

This creates que object like this:

const userFilter = "gma"
const userKey = "email"
let findObj = {}
findObj[userKey] = {$regex:userFilter,$options:"i"}
console.log(findObj)

What is the same that in this query

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

1 Comment

Thanks mate. this should do

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.