node.js - 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?
解决方案
尝试这个
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 ]
你可以在这里测试
推荐阅读
- html - 时间验证(不时)
- laravel - 调用关系返回错误“最大执行时间为 60 秒”
- deep-learning - PyTorch 在第一个可用的 GPU (cuda:0) 上分配更多内存
- kotlin - 有没有办法让 NavigationView 占用更少的代码(Kotlin)
- nginx - nginx 代理服务器上的连接问题(可能是 socket.io 问题)
- java - 在 ANTLR4 词法分析器中,如何定义用例后面的负面外观
- azure - 在 JWT 令牌中包含 AAD 组名称
- javascript - 如何使用 jest 访问导出函数的对象以进行单元测试
- spring-boot - 是否可以在 Spring Boot 中设置没有注释的 http 路由?
- linux - 我想在我的 linux 服务器 (.sh) 中设置 cron 作业。但我有一个错误