繁体   English   中英

如何使用带有 MongoDB. 的正则表达式在数组中查找字符串?

[英]How to look for strings in array using regex with MongoDB.?

我有几个这样的对象:

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

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

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

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

Video.find(query)

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

任何想法? 谢谢。

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

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 });
});

了解 $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 });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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