Skip to content

Commit

Permalink
fix(schema+document): allow disabling _id on subdocuments by default
Browse files Browse the repository at this point in the history
Re: #11541
Re: #8883
  • Loading branch information
vkarpov15 committed Jun 12, 2022
1 parent f4d7ad8 commit f1c5412
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 2 deletions.
1 change: 0 additions & 1 deletion lib/document.js
Expand Up @@ -136,7 +136,6 @@ function Document(obj, fields, skipId, options) {
// excluded fields
if (utils.isPOJO(fields)) {
exclude = isExclusive(fields);

this.$__.fields = fields;
this.$__.exclude = exclude;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/options/SchemaTypeOptions.js
Expand Up @@ -130,7 +130,7 @@ Object.defineProperty(SchemaTypeOptions.prototype, 'ref', opts);
* @instance
*/

Object.defineProperty(SchemaTypeOptions.prototype, 'refPath', opts);
Object.defineProperty(SchemaTypeOptions.prototype, 'refPath', opts);

/**
* Whether to include or exclude this path by default when loading documents
Expand Down
1 change: 1 addition & 0 deletions lib/schema.js
Expand Up @@ -1202,6 +1202,7 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
}

if (type && type.instanceOfSchema) {

return new MongooseTypes.Subdocument(type, path, obj);
}

Expand Down
7 changes: 7 additions & 0 deletions lib/schema/SubdocumentPath.js
Expand Up @@ -33,6 +33,13 @@ module.exports = SubdocumentPath;
*/

function SubdocumentPath(schema, path, options) {
const schemaTypeIdOption = SubdocumentPath.defaultOptions &&
SubdocumentPath.defaultOptions._id;
if (schemaTypeIdOption != null) {
options = options || {};
options._id = schemaTypeIdOption;
}

schema = handleIdOption(schema, options);

this.caster = _createConstructor(schema);
Expand Down
1 change: 1 addition & 0 deletions test/common.js
Expand Up @@ -84,6 +84,7 @@ module.exports = function(options) {

const noErrorListener = !!options.noErrorListener;
delete options.noErrorListener;
options.enableUtf8Validation = false;

const conn = mongoose.createConnection(uri, options);

Expand Down
18 changes: 18 additions & 0 deletions test/schema.subdocumentpath.test.js
Expand Up @@ -181,4 +181,22 @@ describe('SubdocumentPath', function() {

mongoose.Schema.Types.Subdocument.set('required', false);
});

it('supports setting _id globally (gh-11541) (gh-8883)', function() {
mongoose.deleteModel(/Test/);
mongoose.Schema.Types.Subdocument.set('_id', false);

const Model = mongoose.model('Test', mongoose.Schema({
nested: mongoose.Schema({
test: String
})
}));

const doc = new Model({ nested: {} });

assert.ok(!doc.nested._id);

delete mongoose.Schema.Types.Subdocument.defaultOptions._id;
mongoose.Schema.Types.Subdocument.set('required', false);
});
});

0 comments on commit f1c5412

Please sign in to comment.