From 25f74bf997a65e18683433b7eeb43ba5c44f60a1 Mon Sep 17 00:00:00 2001 From: Chris Chapman Date: Wed, 18 Mar 2020 10:29:34 +0000 Subject: [PATCH] Add support for 'add' operation without position. Spec (https://tools.ietf.org/html/rfc6902#section-4.1) requires this operation to replace an existing target field or add a new one, both of which are covered by the same $set mongodb operation. --- index.js | 7 ++++--- test/index.test.js | 26 ++++++++++++++++---------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/index.js b/index.js index 8c7027c..9767577 100644 --- a/index.js +++ b/index.js @@ -15,9 +15,8 @@ module.exports = function(patches){ var key = parts.slice(0, -1).join('.'); var $position = positionPart && parseInt(positionPart, 10) || null; - update.$push = update.$push || {}; - if ($position !== null) { + update.$push = update.$push || {}; if (update.$push[key] === undefined) { update.$push[key] = { $each: [p.value], @@ -35,6 +34,7 @@ module.exports = function(patches){ update.$push[key].$position = Math.min($position, update.$push[key].$position); } } else if(addToEnd) { + update.$push = update.$push || {}; if (update.$push[key] === undefined) { update.$push[key] = p.value; } else { @@ -49,7 +49,8 @@ module.exports = function(patches){ update.$push[key].$each.push(p.value); } } else { - throw new Error("Unsupported Operation! can't use add op without position"); + update.$set = update.$set || {}; + update.$set[toDot(p.path)] = p.value; } break; case 'remove': diff --git a/test/index.test.js b/test/index.test.js index f868581..9b8f99e 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -20,6 +20,22 @@ describe('jsonpatch to mongodb', function() { assert.deepEqual(toMongodb(patches), expected); }); + it('should allow add to insert or replace a non-array field', function() { + var patches = [{ + op: 'add', + path: '/name/nested', + value: 'dave' + }]; + + var expected = { + $set: { + 'name.nested': 'dave' + } + }; + + assert.deepEqual(toMongodb(patches), expected); + }); + it('should work with escaped characters', function() { var patches = [{ op: 'replace', @@ -270,16 +286,6 @@ describe('jsonpatch to mongodb', function() { chai.expect(function(){toMongodb(patches)}).to.throw("Unsupported Operation! can't use add op with mixed positions"); }); - it('should blow up on add without position', function() { - var patches = [{ - op: 'add', - path: '/name', - value: 'dave' - }]; - - chai.expect(function(){toMongodb(patches)}).to.throw("Unsupported Operation! can't use add op without position"); - }); - it('should blow up on move', function() { var patches = [{ op: 'move',