Search code examples
node.jsmongodbmongoose

Fetching documents based of multiply values


My documents have categories. it can be both a single or many ("category 1, category 2,..)

I have been trying to use regular expressions in order to fetch using the following code, so far with no luck:

  const categoriesStr = category.replace(",", "|");
  params.category = `\\${categoriesStr}\\`;


Solution

  • I assume you're trying to do something like this:

    const category = "category 1, category 2"
    const categoriesStr = category.replace(/,\s*/g, "|"); // Replace all commas with "|"
    const params = {};
    params.category = new RegExp(`^(${categoriesStr})$`, "i"); // Create a regular expression
    
    console.log(params.category);