Nodejs + MongoDB模糊搜索

MongoDB中模糊查询要使用正则表达式,使用nodejs和mongodb实现一个通过搜索框对数据库进行搜索的功能,一开始直接用的findOne()方法

1
2
3
Corpus.findOne({name: '/'+req.query.name.replace(/"/g, '')+'/'}, function (err, Corpus) {
...
})

很奇怪,这种方式并查不到东西,把name对应的值写死后,却可以正常查到内容,但是req.query.name是可以正常获取到前台输入的内容的。

解决:

在nodejs中要用RegExp构建正则表达式对象

1
2
3
4
5
6
7
let CorpusSearch = req.query.name.replace(/"/g, '')
let str = ".*"+CorpusSearch+".*$"
let reg = new RegExp(str)

Corpus.find({name:{$regex:reg, $options: 'i'}}, function (err, Corpus) {
...
})

功能完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
.get('/Corpus', function(req, res) {
if (req.query.name != null && req.query.name != undefined && req.query.name != '') {
let CorpusSearch = req.query.name.replace(/"/g, '')
let str = ".*"+CorpusSearch+".*$"
let reg = new RegExp(str)

Corpus.find({name:{$regex:reg, $options: 'i'}}, function (err, Corpus) {
if (err) {
return res.status(500).send('Server error')
}
// console.log(Corpus)
if (Corpus == undefined) {
res.render('Corpus.html', {
count: 0,
Corpus: Corpus
})
} else {
let str = JSON.stringify(Corpus)
Corpus = JSON.parse(str)
res.render('Corpus.html', {
count: 1,
Corpus: Corpus
})
}
})
} else {
Corpus.find(function (err, CorpusData) {
if (err) {
return res.status(500).send('Server error')
}
if (CorpusData.length >= 3) {
var top = [
CorpusData[0],
CorpusData[1],
CorpusData[2],
]
}
res.render('Corpus.html', {
top: top,
Corpus: CorpusData
})
})
}
})

END

Nodejs + MongoDB模糊搜索

http://example.com/index/d05c/

作者

WZJ

发布于

2021-05-29

许可协议

评论