我有一个这样的架构:
{
_id: ObjectId("5a7acda13b808dbed05d6b7e"),
name: "An Apple eat by Man"
}
为此,我编写了查询,即:
db.Collection.find({post: { $regex: req.body.query, $options: "i" }})
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error)
})
因此,对于该查询,如果我写“ Apple”,它将返回数据,但是如果我写“ eat man”,则它将不返回数据。
任何人猜我在哪里做错了,真的很感谢任何帮助或建议
答案 0 :(得分:0)
问题是您的正则表达式。使用正则表达式/eat man/
会查找完全包含"eat man"
而不是单独的单词本身的字符串。
示例:
console.log(/eat Man/.test('An Apple eat by Man'));
console.log(/eat by Man/.test('An Apple eat by Man'));
console.log(/eat Man/.test('An Apple eat by Man'));
console.log(/eat by Man/.test('An Apple eat by Man'));
您可以将正则表达式更改为“匹配包含'eat'和'man'的任何字符串”,例如:
console.log(/eat.*Man/.test('An Apple eat by Man'));
您可以这样做:
// $regex: req.body.query
const req = {
body: {
query: 'Man eat',
},
};
// Will generate something like (?=.*Man)(?=.*eat)
const regex = req.body.query.split(' ').map(x => `(?=.*${x})`).join('');
console.log((new RegExp(regex, 'i')).test('An apply eat by man'));