2

I have a mongodb of recipes and I want to dynamically create a general search query resulting in:

{ $all: [/potato/i, /onion/i, /garlic/i, /chicken/i] }

Without quotation marks from a string like:

const str = 'potato onion garlic chicken'

I've attempted:

const arr = []
str.split(' ').forEach(element => {
  arr.push(`/${element}/i`)
})
console.log(arr)

The problem is I end up with strings:

//[ '/potato/i', '/onion/i', '/garlic/i', '/chicken/i' ]

How do can I dynamically create this query without stringifying?

2 Answers 2

2

Try this

const str = 'potato onion garlic chicken'
const arr = []
str.split(' ').forEach(element => {
    // arr.push(`/${element}/i`)
    arr.push(new RegExp(element, 'i'))
})
console.log(arr)  // [ /potato/i, /onion/i, /garlic/i, /chicken/i ]

You can test here

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

Comments

1

Just a similar version I have tried:

const foodArr = 'potato onion garlic chicken';
queryArr = [];

foodArr.split(' ').forEach(foodElem => {
    queryArr.push(new RegExp(`${foodElem}`, 'i'));
});

console.log(queryArr);

Comments

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.