From 06691f6a34c3d17ef5ea6e4fd4e429c0c1962fa2 Mon Sep 17 00:00:00 2001 From: Katherine Walker Date: Tue, 22 May 2018 15:29:46 -0400 Subject: [PATCH] fix(parsing): support encoding and decoding RegExps Fixes NODE-1464 --- lib/ext_json.js | 8 +++++++- test/extend_mongodb_tests.js | 9 +++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/ext_json.js b/lib/ext_json.js index b92f79c..3d12f41 100644 --- a/lib/ext_json.js +++ b/lib/ext_json.js @@ -230,8 +230,14 @@ function serializeDocument(doc, options) { } else if (val != null && typeof val === 'object') { _doc[name] = serializeDocument(val, options); } - _doc[name] = serializeValue(val, options); + if (val instanceof RegExp) { + let flags = val.flags; + if (flags === undefined) { + flags = val.toString().match(/[gimuy]*$/)[0]; + } + _doc[name] = codecs['BSONRegExp'].toExtendedJSON({ pattern: val.source, options: flags }); + } } return _doc; diff --git a/test/extend_mongodb_tests.js b/test/extend_mongodb_tests.js index 40c2697..493468d 100644 --- a/test/extend_mongodb_tests.js +++ b/test/extend_mongodb_tests.js @@ -204,6 +204,15 @@ describe('Extended JSON', function() { date: dt }); }); + + it('should allow regexp', function() { + const parsedRegExp = extJSON.stringify({ test: /some-regex/i }, { relaxed: true }); + const parsedBSONRegExp = extJSON.stringify( + { test: new BSONRegExp('some-regex', 'i') }, + { relaxed: true } + ); + expect(parsedRegExp).to.eql(parsedBSONRegExp); + }); }); }); });