简体   繁体   中英

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. There are 3 search bars meaning you can search by name, genre, or platform. 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.

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

Say

Games.findOne({ genre: { $in: regex } })

Gives just the first available item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM