diff --git a/lib/schema/boolean.js b/lib/schema/boolean.js index 37b4d51e0a0..c2640841cf1 100644 --- a/lib/schema/boolean.js +++ b/lib/schema/boolean.js @@ -230,7 +230,10 @@ SchemaBoolean.prototype.castForQuery = function($conditional, val) { */ SchemaBoolean.prototype._castNullish = function _castNullish(v) { - if (typeof v === 'undefined' && this.$$context != null && this.$$context._mongooseOptions.omitUndefined) { + if (typeof v === 'undefined' && + this.$$context != null && + this.$$context._mongooseOptions != null && + this.$$context._mongooseOptions.omitUndefined) { return v; } const castBoolean = typeof this.constructor.cast === 'function' ? diff --git a/lib/schematype.js b/lib/schematype.js index 82dd98ef568..38a3d3dbe8c 100644 --- a/lib/schematype.js +++ b/lib/schematype.js @@ -1461,12 +1461,19 @@ SchemaType.prototype.$conditionalHandlers = { SchemaType.prototype.castForQueryWrapper = function(params) { this.$$context = params.context; if ('$conditional' in params) { - return this.castForQuery(params.$conditional, params.val); + const ret = this.castForQuery(params.$conditional, params.val); + this.$$context = null; + return ret; } if (params.$skipQueryCastForUpdate || params.$applySetters) { - return this._castForQuery(params.val); + const ret = this._castForQuery(params.val); + this.$$context = null; + return ret; } - return this.castForQuery(params.val); + + const ret = this.castForQuery(params.val); + this.$$context = null; + return ret; }; /**