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',