{"record":{"id":"cfa120f9f9003216","repo":"Automattic/mongoose","slug":"cannot-overwrite-name-model-once-compiled","errorCode":null,"errorMessage":"Cannot overwrite `${name}` model once compiled.","messagePattern":"Cannot overwrite `(.+?)` model once compiled\\.","errorType":"exception","errorClass":"OverwriteModelError","httpStatus":null,"severity":"error","filePath":"lib/connection.js","lineNumber":1472,"sourceCode":"\n  if (utils.isObject(schema)) {\n    if (!schema.instanceOfSchema) {\n      schema = new Schema(schema);\n    } else if (!(schema instanceof this.base.Schema)) {\n      schema = schema._clone(this.base.Schema);\n    }\n  }\n  if (schema && !schema.instanceOfSchema) {\n    throw new MongooseError('The 2nd parameter to `mongoose.model()` should be a ' +\n      'schema or a POJO');\n  }\n\n  const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels };\n  const opts = Object.assign(defaultOptions, options, { connection: this });\n  if (this.models[name] && !collection && opts.overwriteModels !== true) {\n    // model exists but we are not subclassing with custom collection\n    if (schema?.instanceOfSchema && schema !== this.models[name].schema) {\n      throw new MongooseError.OverwriteModelError(name);\n    }\n    return this.models[name];\n  }\n\n  let model;\n\n  if (schema?.instanceOfSchema) {\n    applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied');\n\n    // compile a model\n    model = this.base._model(fn || name, schema, collection, opts);\n\n    // only the first model with this name is cached to allow\n    // for one-offs with custom collection names etc.\n    if (!this.models[name]) {\n      this.models[name] = model;\n    }\n","sourceCodeStart":1454,"sourceCodeEnd":1490,"githubUrl":"https://github.com/Automattic/mongoose/blob/49cdab01366679723b487ecb754b38570f783289/lib/connection.js#L1454-L1490","documentation":"Mongoose caches compiled models by name per connection. Re-calling conn.model('X', schema) when 'X' is already compiled throws OverwriteModelError ('Cannot overwrite `X` model once compiled.') unless the schema object is identical, a custom collection name is given, or overwriteModels is enabled (lib/connection.js:1472). The guard protects live model classes and existing documents from being silently swapped.","triggerScenarios":"Calling conn.model('Test', otherSchema) twice with different schema objects on the same connection; most commonly triggered by hot-reload (Next.js/Nuxt dev, nodemon, Jest re-importing model files per test) or seed scripts re-running model definitions.","commonSituations":"Dev hot-reload re-executing model modules; test isolation redefining the same model per suite; duplicate model definitions spread across files; defining a model inside a request handler.","solutions":["Reuse-or-define guard: const Test = mongoose.models.Test ?? mongoose.model('Test', schema)","Reuse the compiled model instead: const Test = conn.model('Test') (name-only lookup)","Delete before redefining: conn.deleteModel('Test')","Opt in explicitly: conn.model('Test', schema, null, { overwriteModels: true }) or globally mongoose.set('overwriteModels', true)"],"exampleFix":"// before\nmodule.exports = mongoose.model('Test', testSchema); // throws on hot reload / re-import\n\n// after\nmodule.exports = mongoose.models.Test ?? mongoose.model('Test', testSchema);","handlingStrategy":"validation","validationCode":"const getModel = (name, schema, collection) =>\n  conn.models[name] ?? conn.model(name, schema, collection);\n// or check explicitly:\nif (conn.modelNames().includes('Test')) {\n  const Test = conn.model('Test'); // reuse existing\n} else {\n  const Test = conn.model('Test', testSchema);\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Use the reuse-or-define guard: mongoose.models.X ?? mongoose.model('X', schema)","Define each model exactly once per process in a dedicated module","Call conn.deleteModel(name) in test teardown before redefining models","Only enable overwriteModels (mongoose.set('overwriteModels', true)) when redefinition is intentional"],"tags":["model","overwrite","hot-reload","duplicate-definition"],"backgroundTag":"duplicate-model-definition","analyzedSha":"49cdab01366679723b487ecb754b38570f783289","analyzedAt":"2026-08-21T22:54:00.882Z","schemaVersion":2},"datasetVersion":"2026-08-21T23:17:16.201Z"}