【问题标题】:How to look for strings in array using regex with MongoDB.?如何在 MongoDB 中使用正则表达式在数组中查找字符串。?
【发布时间】:2020-07-29 15:43:10
【问题描述】:

我有几个这样的对象:

"status": "published",
"term_id": [
   "anime",
   "sci-fi",
   "etc"
],
"captionCert": "1",

我知道为了查看单个字段,我会创建如下内容:

if (keyword) {
  query.status = { $regex: keyword, $options: 'i' };
}

关键字来自前端,可以是用户输入的任何内容;然后我继续查看字段状态,然后通过将其传递到我的模型查询中来检索它:

Video.find(query)

现在的问题是我需要知道如何在 term_id 数组中准确地做到这一点?

有什么想法吗?谢谢。

更新:我正在尝试将它实现到这个函数中:

exports.searchVideos = asyncHandler(async (req, res, next) => {
  const query = {};
  const { keyword } = req.query;

  if (keyword) {
    query.title = { $regex: keyword, $options: 'i' };
  } else {
    query.text = { $regex: keyword, $options: 'i' };
  }

  if (keyword) {
    query.term_id = { term_id: { $regex: keyword, $options: 'i' } };
  };

  const video = await Video.find(query).select(
    'title text thumbnail video_url term_id'
  );
  console.log(query);
  res.status(200).json({ success: true, data: video });
});

【问题讨论】:

    标签: node.js arrays mongodb


    【解决方案1】:

    了解 $or 运算符后的解决方案。这解决了我的问题!:

    exports.searchVideos = asyncHandler(async (req, res, next) => {
      let query = {};
      const { keyword } = req.query;
    
      query = {
        $or: [
          { title: { $regex: keyword, $options: 'i' } },
          { text: { $regex: keyword, $options: 'i' } },
          { term_id: { $regex: keyword, $options: 'i' }}
        ]
      };
    
      const video = await Video.find(query).select(
        'title text thumbnail video_url term_id'
      );
    
      res.status(200).json({ success: true, data: video });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多