首页 > 解决方案 > how to general search from [array] of string

问题描述

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?

标签: node.jsregexmongodbmongoose

解决方案


尝试这个

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 ]

你可以在这里测试


推荐阅读