0

I have several objects like this:

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

I know that in order to look within a single field, I would create something like this:

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

Where keyword comes from the front end and can be whatever the user types; then I proceed to look into the field status and then I just retrieve it by passing it into my model query:

Video.find(query)

Now hte problem is that I need to know how to exactly do this but inside the term_id array?

Any idea? Thanks.

UPDATE: I'm trying to implement it into this 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 });
});

1 Answer 1

1

Solution after finding out about $or operator. This solved my problems!:

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 });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.