Skip to content
This repository was archived by the owner on Dec 20, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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 {
Expand All @@ -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':
Expand Down
26 changes: 16 additions & 10 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand Down