Error using $regexMatch and $regexFind in Aggregation Pipeline within Atlas App Sync Function

Hi All

I have a large aggregation pipeline which runs perfectly fine when tested in VSCode Playground, however when I transfer this into a App Services Function, which would normally be executed using a scheduled trigger I am getting errors with the use of $regex

The error I am receiving is:

Failed to optimize pipeline :: caused by :: $regexMatch needs 'regex' to be of type string or regex

The pipeline stage is as follows

const regExAdPriceExtractStage = {
    $set: {
      regexAdPrice: {
        $cond: {
          if: {
            $regexMatch: {
              input: '$price_text',
              regex: /pw|week|pcm|month|psm|mth|p\.c\.m|pm|p\/m|p\.m|sqm|m2/,
              options: 'i',
            },
          },
          then: '$$REMOVE',
          else: {
            $regexFind: {
              input: '$price_text',
              regex: /(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d{1,2})?(?!\.?\d)/,
              options: 'i',
            },
          },
        },
      },
    },
  };

It looks at a price_text field and will either remove the field if some patters match, or it will extract a monetary amount from the field.

Reading the docs https://www.mongodb.com/docs/manual/reference/operator/aggregation/regexMatch/ it says that I can use the pattern /<pattern>/ but for some reason this does not run when in an App Services Function.

Thanks heaps.

So I think I figured it out. The only way I could get it to work is to use BSON.BSONRegExp as per this note here: https://www.mongodb.com/docs/atlas/app-services/functions/mongodb/read/#evaluate-a-regular-expression. The pipeline stage now being:

const regExAdPriceExtractStage = {
    $set: {
      regexAdPrice: {
        $cond: {
          if: {
            $regexMatch: {
              input: '$price_text',
              // eslint-disable-next-line prefer-regex-literals
              regex: new BSON.BSONRegExp('pw|week|pcm|month|psm|mth|p\\.c\\.m|pm|p\\/m|p\\.m|sqm|m2'),
              options: 'i',
            },
          },
          then: '$$REMOVE',
          else: {
            $regexFind: {
              input: '$price_text',
              // eslint-disable-next-line prefer-regex-literals
              regex: new BSON.BSONRegExp('(?:\\d{1,3}(?:,\\d{3})*|\\d+)(?:\\.\\d{1,2})?(?!\\.?\\d)'),
              options: 'i',
            },
          },
        },
      },
    },
  };