diff --git a/lib/document.js b/lib/document.js index cd03cc42495..b89157a904a 100644 --- a/lib/document.js +++ b/lib/document.js @@ -893,7 +893,11 @@ Document.prototype.$set = function $set(path, val, type, options) { keys = Object.keys(path); const len = keys.length; - if (len === 0 && !this.schema.options.minimize) { + // `_skipMinimizeTopLevel` is because we may have deleted the top-level + // nested key to ensure key order. + const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false); + if (len === 0 && (!this.schema.options.minimize || _skipMinimizeTopLevel)) { + delete options._skipMinimizeTopLevel; if (val) { this.$set(val, {}); } @@ -924,6 +928,8 @@ Document.prototype.$set = function $set(path, val, type, options) { this._doc[key] != null && Object.keys(this._doc[key]).length === 0) { delete this._doc[key]; + // Make sure we set `{}` back even if we minimize re: gh-8565 + options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); } if (typeof path[key] === 'object' &&