Skip to content

Commit 97dadf0

Browse files
authored
Merge pull request Automattic#14749 from 0x0a0d/improve_fix_cast_empty_query
Improve fix cast empty query
2 parents 53d382b + e3a9e65 commit 97dadf0

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/cast.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,17 @@ module.exports = function cast(schema, obj, options, context) {
6969
if (val[k] == null || typeof val[k] !== 'object') {
7070
throw new CastError('Object', val[k], path + '.' + k);
7171
}
72+
73+
const beforeCastKeysLength = Object.keys(val[k]).length;
7274
val[k] = cast(schema, val[k], options, context);
75+
if (Object.keys(val[k]).length === 0 && beforeCastKeysLength !== 0) {
76+
val.splice(k, 1);
77+
}
78+
}
79+
80+
// delete empty: {$or: []} -> {}
81+
if (val.length === 0) {
82+
delete obj[path];
7383
}
7484
} else if (path === '$where') {
7585
type = typeof val;

test/docs/cast.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,26 @@ describe('Cast Tutorial', function() {
136136
'strictQuery is \'throw\'.');
137137
// acquit:ignore:end
138138
});
139+
140+
it('strictQuery removes casted empty objects', async function() {
141+
mongoose.deleteModel('Character');
142+
const schema = new mongoose.Schema({ name: String, age: Number }, {
143+
strictQuery: true
144+
});
145+
Character = mongoose.model('Character', schema);
146+
147+
const query = Character.findOne({
148+
$or: [{ notInSchema: { $lt: 'not a number' } }],
149+
$and: [{ name: 'abc' }, { age: { $gt: 18 } }, { notInSchema: { $lt: 'not a number' } }],
150+
$nor: [{}] // should be kept
151+
});
152+
153+
await query.exec();
154+
query.getFilter(); // Empty object `{}`, Mongoose removes `notInSchema`
155+
// acquit:ignore:start
156+
assert.deepEqual(query.getFilter(), { $and: [{ name: 'abc' }, { age: { $gt: 18 } }], $nor: [{}] });
157+
// acquit:ignore:end
158+
});
139159

140160
it('implicit in', async function() {
141161
// Normally wouldn't find anything because `name` is a string, but

0 commit comments

Comments
 (0)