diff --git a/lib/mongo-object.js b/lib/mongo-object.js index a93309e..5e6f192 100644 --- a/lib/mongo-object.js +++ b/lib/mongo-object.js @@ -671,16 +671,17 @@ export default class MongoObject { /* STATIC */ - /* Takes a specific string that uses mongo-style dot notation - * and returns a generic string equivalent. Replaces all numeric - * "pieces" with a dollar sign ($). + /* Takes a specific string that uses any mongo-style positional update + * dot notation and returns a generic string equivalent. Replaces all numeric + * positional "pieces" (e.g. '.1') or any other positional operator + * (e.g. '$[]') with a dollar sign ($). * * @param {type} name * @returns {String} Generic name. */ static makeKeyGeneric(key) { if (typeof key !== 'string') return null; - return key.replace(/\.[0-9]+(?=\.|$)/g, '.$'); + return key.replace(/\.([0-9]+|\$\[[^\]]*\])(?=\.|$)/g, '.$'); } /** Takes a string representation of an object key and its value diff --git a/lib/mongo-object.test.js b/lib/mongo-object.test.js index 019b790..d6a65f6 100644 --- a/lib/mongo-object.test.js +++ b/lib/mongo-object.test.js @@ -201,8 +201,18 @@ describe('MongoObject', () => { }); it('makeKeyGeneric', () => { - const generic = MongoObject.makeKeyGeneric('foo.0.0.ab.c.123.4square.d.67e.f.g.1'); - expect(generic).toEqual('foo.$.$.ab.c.$.4square.d.67e.f.g.$'); + function testMakeKeyGeneric(input, expectedOutput) { + const generic = MongoObject.makeKeyGeneric(input); + expect(generic).toEqual(expectedOutput); + } + testMakeKeyGeneric(0, null); + testMakeKeyGeneric({}, null); + testMakeKeyGeneric('foo', 'foo'); + testMakeKeyGeneric('foo.bar', 'foo.bar'); + testMakeKeyGeneric('foo.$', 'foo.$'); + testMakeKeyGeneric('foo.0.0.ab.c.123.4square.d.67e.f.g.1', 'foo.$.$.ab.c.$.4square.d.67e.f.g.$'); + testMakeKeyGeneric('foo.$[].foo.$[bar].$.$[]', 'foo.$.foo.$.$.$'); + testMakeKeyGeneric('foo.$foo.$foo[bar]foo.foo$[].foo$[bar]', 'foo.$foo.$foo[bar]foo.foo$[].foo$[bar]'); }); it('cleanNulls', () => {