Skip to content

Commit

Permalink
Add support for $pull update operator
Browse files Browse the repository at this point in the history
  • Loading branch information
erikolson186 committed Jul 9, 2017
1 parent f1cea70 commit 5c59a06
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ The following expression operators are supported: `$literal`, `$add`, `$subtract

### Update Operators

The following update operators are supported: `$set`, `$unset`, `$rename`, `$inc`, `$mul`, `$min`, `$max`, `$push`, and `$pop`.
The following update operators are supported: `$set`, `$unset`, `$rename`, `$inc`, `$mul`, `$min`, `$max`, `$push`, `$pop`, and `$pull`.

### Group Operators

Expand Down
16 changes: 14 additions & 2 deletions src/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
modify,
remove1,
rename,
equal,
unknownOp,
getIDBError
} = require('./util.js');
Expand Down Expand Up @@ -51,7 +52,7 @@ const compareOp = (fn) => (path_pieces, value) => {
};

const $min = compareOp((a, b) => a < b);
const $max = compareOp((a, b) => a > b);
const $max = compareOp((a, b) => a > b);

const $push = (path_pieces, value) => {
const update = (obj, field) => {
Expand Down Expand Up @@ -85,6 +86,16 @@ const $pop = (path_pieces, direction) => {
};
};

const $pull = (path_pieces, value) => (doc) => {
get(doc, path_pieces, (obj, field) => {
const elements = obj[field];
if (!Array.isArray(elements)) { return; }

const filterFn = el => !equal(el, value);
obj[field] = elements.filter(filterFn);
});
};

const ops = {
$set,
$unset,
Expand All @@ -94,7 +105,8 @@ const ops = {
$min,
$max,
$push,
$pop
$pop,
$pull
};

const build = (steps, field, value) => {
Expand Down
16 changes: 15 additions & 1 deletion test/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ describe('$push', () => {
});

describe('$pop', () => {
it('should remove a value of an array', (done) => {
it('should remove the first or last element of an array', (done) => {
update({
$pop: { a: 1, n: -1 }
}, {
Expand All @@ -234,3 +234,17 @@ describe('$pop', () => {
}, done);
});
});

describe('$pull', () => {
it('should remove instances of a value from an array', (done) => {
update({
$pull: { a: 4 }
}, {
k: 3,
t: 4,
a: [3],
n: [8, 2],
m: { x: 80 }
}, done);
});
});

0 comments on commit 5c59a06

Please sign in to comment.