Skip to content

Commit 6555d92

Browse files
committed
support deeper update
Signed-off-by: Romy <romy2232@gmail.com>
1 parent 2f9b622 commit 6555d92

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

test/update.js

+3
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ describe('update: ', function() {
2323
it('$set deep', function() {
2424
assert.equal(convertUpdate('data', { $set: { 'a.b': 2 } }), 'jsonb_set(jsonb_set(data,\'{a}\',COALESCE(data->\'a\', \'{}\'::jsonb)),\'{a,b}\',\'2\'::jsonb)')
2525
})
26+
it('$set deep 2', function() {
27+
assert.equal(convertUpdate('data', { $set: { 'a.b.c': 2 } }), 'jsonb_set(jsonb_set(jsonb_set(data,\'{a}\',COALESCE(data->\'a\', \'{}\'::jsonb)),\'{a,b}\',COALESCE(data->\'a\'->\'b\', \'{}\'::jsonb)),\'{a,b,c}\',\'2\'::jsonb)')
28+
})
2629
it('$set fails for _id', function() {
2730
assert.throws(() => convertUpdate('data', { $set: { _id: 'b' } }), 'Mod on _id not allowed')
2831
})

update.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ function convertOp(input, op, data, fieldName, upsert) {
1818
// Create the necessary top level keys since jsonb_set will not create them automatically.
1919
if (path.length > 1) {
2020
for (let i = 0; i < path.length - 1; i++) {
21-
const parentPath = util.toPostgresPath([path[i]])
21+
const slice = path.slice(0, i + 1)
22+
const parentPath = util.toPostgresPath(slice)
2223
if (!input.includes(parentPath)) {
23-
const parentValue = upsert ? '\'{}\'::jsonb' : `COALESCE(${util.pathToText([fieldName].concat(path.slice(0, i + 1)))}, '{}'::jsonb)`
24+
const parentValue = upsert ? '\'{}\'::jsonb' : `COALESCE(${util.pathToText([fieldName].concat(slice))}, '{}'::jsonb)`
2425
input = 'jsonb_set(' + input + ',' + parentPath + ',' + parentValue + ')'
2526
}
2627
}

0 commit comments

Comments
 (0)