Jona Becher
Jona Becher

Reputation: 35

How to create a dynamic query in MongoDB?

I tried to write a dynamic query in mongoose, but I couldn't find a way to achieve my goal.

I want to program a video platform that includes an advanced video search function. Here is a snippet of my code:

router.get("/search/video", async (req, res) => {
  let category = JSON.parse(req.query.category); // Array
  let searchOrder = req.query.searchOrder; // String
  let searchText = req.query.searchText; // String
  let channel = req.query.channel; // String

  //query, if all parameters are provided

  Video.find({
    $text: { $search: searchText, $language: "en" },
    category: { $elemMatch: { categoryID: { $in: category } } },
    channelID: channel,
  }).sort({ date_added: searchOrder });
});

However, if the user does not want to search for a specific category or does not specify a channel, null is transmitted and no suitable video can be found. I tried to use a string, but it doesn't work with model.findOne (). How can I program a dynamic query that works depending on the given parameters?

Thanks in advance!

Upvotes: 1

Views: 135

Answers (1)

AKX
AKX

Reputation: 169378

Simply build that query object from the request bits, ignoring those that would be falsy:

const query = {};
if (searchText) {
  query.$text = { $search: searchText, $language: "en" };
}
if (category && category.length) {
  query.category = { $elemMatch: { categoryID: { $in: category } } };
}
if (channel) {
  query.channelID = channel;
}

Video.find(query).sort({ date_added: searchOrder });

Upvotes: 2

Related Questions