diff --git a/lib/schema.js b/lib/schema.js index 5177e5c9590..e706378e6b2 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -434,8 +434,8 @@ Schema.prototype.pick = function(paths, options) { Schema.prototype.defaultOptions = function(options) { this._userProvidedOptions = options == null ? {} : utils.clone(options); const baseOptions = this.base && this.base.options || {}; - const strict = 'strict' in baseOptions ? baseOptions.strict : true; + const id = 'id' in baseOptions ? baseOptions.id : true; options = utils.options({ strict: strict, strictQuery: 'strict' in this._userProvidedOptions ? @@ -454,7 +454,7 @@ Schema.prototype.defaultOptions = function(options) { validateBeforeSave: true, // the following are only applied at construction time _id: true, - id: true, + id: id, typeKey: 'type' }, utils.clone(options)); diff --git a/lib/validoptions.js b/lib/validoptions.js index 0f7b697c415..a42e552c7af 100644 --- a/lib/validoptions.js +++ b/lib/validoptions.js @@ -15,6 +15,7 @@ const VALID_OPTIONS = Object.freeze([ 'bufferTimeoutMS', 'cloneSchemas', 'debug', + 'id', 'timestamps.createdAt.immutable', 'maxTimeMS', 'objectIdGetter', diff --git a/test/index.test.js b/test/index.test.js index 9c80b5ae644..831b817f7a5 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1086,4 +1086,22 @@ describe('mongoose module:', function() { assert.deepEqual(res.toObject(), { answer: 42 }); }); }); + describe('global id option', function() { + it('can disable the id virtual on schemas gh-11966', async function() { + const m = new mongoose.Mongoose(); + m.set('id', false); + + const db = await m.connect(start.uri); + + const schema = new m.Schema({ title: String }); + + const falseID = db.model('gh11966', schema); + + + const entry = await falseID.create({ + title: 'The IDless master' + }); + assert.equal(entry.id, undefined); + }); + }); }); diff --git a/types/mongooseoptions.d.ts b/types/mongooseoptions.d.ts index dabae7e5333..b470e1aa9b6 100644 --- a/types/mongooseoptions.d.ts +++ b/types/mongooseoptions.d.ts @@ -79,6 +79,12 @@ declare module 'mongoose' { | stream.Writable | ((collectionName: string, methodName: string, ...methodArgs: any[]) => void); + /** + * If `true`, adds a `id` virtual to all schemas unless overwritten on a per-schema basis. + * @defaultValue true + */ + id?: boolean; + /** * If `false`, it will change the `createdAt` field to be [`immutable: false`](https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-immutable) * which means you can update the `createdAt`.