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

Commit b8fffea

Browse files
Bajiximlucas
authored andcommitted
Parse add positions (#7)
1 parent 9c96467 commit b8fffea

File tree

2 files changed

+88
-8
lines changed

2 files changed

+88
-8
lines changed

index.js

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,48 @@ module.exports = function(patches){
44
var update = {};
55
patches.map(function(p){
66
if(p.op === 'add'){
7-
var path = toDot(p.path);
8-
if(!update.$push) update.$push = {};
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]]};
7+
var path = toDot(p.path),
8+
parts = path.split('.');
9+
10+
var key = parts[0];
11+
var $position = parts[1] && parseInt(parts[1], 10);
12+
13+
update.$push = update.$push || {};
14+
15+
if (!isNaN($position)) {
16+
if (update.$push[key]) {
17+
if (!isNaN(update.$push[key].$position)) {
18+
$position = update.$push[key].$position;
19+
delete update.$push[key].$position;
20+
}
21+
22+
if (!update.$push[key].$each) {
23+
update.$push[key] = {
24+
$each: [
25+
update.$push[key]
26+
]
27+
};
28+
}
29+
30+
update.$push[key].$each.push(p.value);
31+
update.$push[key].$position = $position;
32+
} else {
33+
update.$push[key] = {
34+
$each: [p.value],
35+
$position: $position
36+
};
37+
}
38+
} else {
39+
if (update.$push[key]) {
40+
if (!update.$push[key].$each) {
41+
update.$push[key] = {
42+
$each: [update.$push[key]]
43+
};
44+
}
45+
update.$push[path].$each.push(p.value);
46+
} else {
47+
update.$push[path] = p.value;
1448
}
15-
update.$push[path].$each.push(p.value);
1649
}
1750
}
1851
else if(p.op === 'remove'){

test/index.test.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,53 @@ describe('jsonpatch to mongodb', function() {
2020
assert.deepEqual(toMongodb(patches), expected);
2121
});
2222

23+
it('should work with array set', function() {
24+
var patches = [{
25+
op: 'add',
26+
path: '/name/1',
27+
value: 'dave'
28+
}];
29+
30+
var expected = {
31+
$push: {
32+
name: {
33+
$each: [
34+
'dave'
35+
],
36+
$position: 1
37+
}
38+
}
39+
};
40+
41+
assert.deepEqual(toMongodb(patches), expected);
42+
});
43+
44+
it('should work with multiple set', function() {
45+
var patches = [{
46+
op: 'add',
47+
path: '/name/1',
48+
value: 'dave'
49+
}, {
50+
op: 'add',
51+
path: '/name/2',
52+
value: 'bob'
53+
}];
54+
55+
var expected = {
56+
$push: {
57+
name: {
58+
$each: [
59+
'dave',
60+
'bob'
61+
],
62+
$position: 1
63+
}
64+
}
65+
};
66+
67+
assert.deepEqual(toMongodb(patches), expected);
68+
});
69+
2370
it('should work with multiple adds', function() {
2471
var patches = [{
2572
op: 'add',

0 commit comments

Comments
 (0)