[英]How to find one item in an array in mongodb/mongoose and nodejs
I'm building a fuzzy game search to search through the games in mongodb and display the items that match. 我正在建立一个模糊的游戏搜索,以搜索mongodb中的游戏并显示匹配的项目。 There are 3 search bars meaning you can search by name, genre, or platform. 共有3个搜索栏,您可以按名称,类型或平台进行搜索。 The genre and platform are stored in arrays in the database and I cannot figure out how to see if one of the items in an array matches the search term. 流派和平台存储在数据库的数组中,我无法弄清楚如何查看数组中的一项是否与搜索词匹配。 It works when there is only one item in the array, but if there are 2 or more, it doesn't work. 当数组中只有一项时,它可以工作,但是如果有两项或更多,则它不起作用。
this is what I have now: 这就是我现在所拥有的:
if (req.query.searchGenre) {
const regex = new RegExp(escapeRegex(req.query.searchGenre), "gi")
Games.find({ genre: { $in: regex } }, (err, games) => {
console.log(regex)
if (err) {
console.log(err)
} else {
res.render("index", { games: games })
}
})
}
I have tried all of the array query selectors from the mongodb docs and those aren't working. 我已经尝试过mongodb文档中的所有数组查询选择器,但这些都不起作用。
If you have any ideas, I'd greatly appreciate it! 如果您有任何想法,我将不胜感激!
如果我正确理解并且您的查询尝试将genre
数组中的任何元素与搜索模式进行匹配,则$ elemMatch和$ regex是您想要的运算符
Games.find({ genre: { $elemMatch: { $regex: regex } } }, ...)
MogoDb has a findOne() method you can call MogoDb有一个findOne()方法可以调用
Say 说
Games.findOne({ genre: { $in: regex } })
Gives just the first available item 仅给出第一个可用项目
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.