Skip to content

Commit

Permalink
fix(castArrayFilters): handle casting multiple array filters
Browse files Browse the repository at this point in the history
Re: #7079
  • Loading branch information
vkarpov15 committed Jan 13, 2019
1 parent d483040 commit c53a52a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lib/helpers/update/castArrayFilters.js
Expand Up @@ -35,17 +35,23 @@ module.exports = function castArrayFilters(query) {
}
const firstKey = Object.keys(filter)[0];

if (filter[firstKey] == null) {
continue;
}

const dot = firstKey.indexOf('.');
const filterPath = dot === -1 ?
let filterPath = dot === -1 ?
updatedPathsByFilter[firstKey] + '.0' :
updatedPathsByFilter[firstKey.substr(0, dot)] + '.0' + firstKey.substr(dot);

if (filterPath == null) {
throw new Error(`Filter path not found for ${firstKey}`);
}
if (filter[firstKey] == null) {
continue;
}

// If there are multiple array filters in the path being updated, make sure
// to replace them so we can get the schema path.
filterPath = filterPath.replace(/\$\[[^\]]+\]/g, '0');

const schematype = schema.path(filterPath);
if (typeof filter[firstKey] === 'object') {
filter[firstKey] = castFilterPath(query, schematype, filter[firstKey]);
Expand Down
21 changes: 21 additions & 0 deletions test/helpers/update.castArrayFilters.test.js
Expand Up @@ -20,4 +20,25 @@ describe('castArrayFilters', function() {

done();
});

it('casts multiple', function(done) {
const schema = new Schema({
comments: [{
text: String,
replies: [{ date: Date }]
}]
});
const q = new Query();
q.schema = schema;

q.updateOne({}, { $set: { 'comments.$[x].replies.$[y].date': '2018-01-01' } }, {
arrayFilters: [{ 'x.text': 123 }, { 'y.date': { $gte: '2018-01-01' } }]
});
castArrayFilters(q);

assert.strictEqual(q.options.arrayFilters[0]['x.text'], '123');
assert.ok(q.options.arrayFilters[1]['y.date'].$gte instanceof Date);

done();
});
});

0 comments on commit c53a52a

Please sign in to comment.