Skip to content
This repository was archived by the owner on Dec 20, 2023. It is now read-only.

Commit 9b5574c

Browse files
committed
Merge pull request #4 from apierzch/master
support adding multiple values to array
2 parents 11791b8 + b159ccb commit 9b5574c

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

index.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,16 @@ module.exports = function(patches){
44
var update = {};
55
patches.map(function(p){
66
if(p.op === 'add'){
7+
var path = toDot(p.path);
78
if(!update.$push) update.$push = {};
8-
update.$push[toDot(p.path)] = p.value;
9+
if(!update.$push[path]) {
10+
update.$push[path] = p.value;
11+
} else if (update.$push[path]) {
12+
if(!update.$push[path].$each) {
13+
update.$push[path] = {$each : [update.$push[path]]};
14+
}
15+
update.$push[path].$each.push(p.value);
16+
}
917
}
1018
else if(p.op === 'remove'){
1119
if(!update.$unset) update.$unset = {};

test/index.test.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ var chai = require('chai');
44

55
describe('jsonpatch to mongodb', function() {
66

7-
it('should work with add', function() {
7+
it('should work with single add', function() {
88
var patches = [{
99
op: 'add',
1010
path: '/name',
@@ -20,6 +20,30 @@ describe('jsonpatch to mongodb', function() {
2020
assert.deepEqual(toMongodb(patches), expected);
2121
});
2222

23+
it('should work with multiple adds', function() {
24+
var patches = [{
25+
op: 'add',
26+
path: '/name',
27+
value: 'dave'
28+
},{
29+
op: 'add',
30+
path: '/name',
31+
value: 'bob'
32+
},{
33+
op: 'add',
34+
path: '/name',
35+
value: 'john'
36+
}];
37+
38+
var expected = {
39+
$push: {
40+
name: {$each: ['dave', 'bob', 'john']}
41+
}
42+
};
43+
44+
assert.deepEqual(toMongodb(patches), expected);
45+
});
46+
2347
it('should work with remove', function() {
2448
var patches = [{
2549
op: 'remove',

0 commit comments

Comments
 (0)