简体   繁体   English

如何在mongodb / mongoose和Node.js中的数组中找到一项

[英]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.

相关问题 NodeJs MongoDb Mongoose-如何从多维数组中删除项目? - NodeJs MongoDb Mongoose - How to Delete item from Multi Dimensional Array? 如何在 mongoose/mongodb 和 nodejs 中对对象数组进行排序? - How to sort array of object in mongoose/mongodb and nodejs? 返回nodejs和mongodb中嵌套数组的一项 - Return one item of a nested array in nodejs and mongodb 如何在 mongodb nodejs 中查找数组 - how to find array in mongodb nodejs 如何使用过滤器 _id 找到一条记录并使用 nodejs 和 mongodb,mongoose 更新该记录 - how can i find one record with the filter _id and update that record using the nodejs and mongodb,mongoose 如何通过 MongoDB (Mongoose) 中的“_id”字段查找文档的数组项? - How to find document's array item by its "_id" field in MongoDB (Mongoose)? 如何从Node.js中的find返回,mongoose mongodb集合 - How to return from find in nodejs,mongoose mongodb collection 如何在Mongoose MongoDb NodeJS中的数组中获取集合中的连接对象 - How to get the connected objects within a collection in an array in Mongoose MongoDb NodeJS 如何从Mongodb到Mongoose的嵌套文档中获取Nodejs中的数组? - How to get an Array in Nodejs from a nested document in Mongodb through Mongoose? 如何使用 mongoose 和 NodeJs 在 Mongodb 的数组字段中插入数据 - How to insert data in array field in Mongodb using mongoose and NodeJs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM