[英]Mongoose search using regex and ignoring special characters
I want to make a serachbar for my site.我想为我的网站制作一个搜索栏。 I'm really new using express and mongoose.我真的是使用 express 和 mongoose 的新手。
This my code that works fine but in this case it doesn't give matches:这是我的代码可以正常工作,但在这种情况下它不匹配:
Search input: Mass energy
Entry name: Mass-energy equivalence
This doesn't match because of the dash/hyphen, how can I ignore it in $regex?由于破折号/连字符,这不匹配,我如何在 $regex 中忽略它? Or if there is another better way to do this, let me know.或者,如果有其他更好的方法可以做到这一点,请告诉我。 Thanks in advance!提前致谢!
Code代码
router.get('/search/:search', param('search').not().isEmpty().trim().escape(), async (req, res) => {
let search = req.params.search.replace(/[^\w\s]/gi, '');
const data = await Entry.find({
'name': {
'$regex': search,
'$options': 'i'
}
},
)
.populate('category')
.limit(10);
res.json(data);
});
Thanks to @boly38感谢@boly38
Adding replace.replace(" ", '.+')
to search works添加replace.replace(" ", '.+')
到搜索作品
let search = req.params.search.replace(/[^\w\s]/gi, '').replace(" ", '.+');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.