How to fix OverwriteModelError: Cannot overwrite model once compiled in MongoDB

MongoDBBEGINNERMEDIUMUpdated Dec 22, 2025· 151 views

This Mongoose error occurs when trying to register a model with the same name multiple times. It commonly happens in development environments with hot-reloading, serverless functions, or test suites that re-import model files.

Quick fix

Fixes OverwriteModelError: Cannot overwrite model once compiled

// models/User.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  // ... other fields
});

// Check if model exists, otherwise create it
module.exports = mongoose.models.User || mongoose.model('User', userSchema);
  1. Add conditional model export pattern
  2. Ensure single model definition file
  3. Fix test suite model imports
  4. Clear Mongoose connection in tests (if needed)
mongodb — error
// models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
// ... other fields
});
// Check if model exists, otherwise create it
module.exports = mongoose.models.User || mongoose.model('User', userSchema);
OverwriteModelError: Cannot overwrite model once compiled

What this error means

This error is thrown by Mongoose (the MongoDB ODM) when you attempt to compile a model that has already been registered in the Mongoose instance. Mongoose maintains a global registry of all compiled models in `mongoose.models`, and once a model is compiled with a specific name, it cannot be overwritten without clearing the registry first. The error typically occurs because Mongoose is designed to prevent accidental model redefinition, which could lead to inconsistent schema definitions and unpredictable behavior. When your application tries to call `mongoose.model('User', userSchema)` twice, Mongoose detects the duplicate registration and throws this error to prevent conflicts. This is particularly common in Next.js API routes (which are deployed as serverless functions), development environments with hot module replacement (HMR), test suites that reload models before each test, and applications that import model files multiple times through different paths.

Typical symptoms

  • Application crashes with "OverwriteModelError: Cannot overwrite `ModelName` model once compiled"
  • Error occurs when restarting development server with nodemon or hot-reload
  • Tests fail when running multiple test suites that import the same model
  • Next.js API routes throw error on subsequent requests
  • Serverless functions fail after first invocation in development mode

Common causes

  1. Calling mongoose.model() multiple times with the same model name
  2. Hot module replacement (HMR) in development causing model files to reload
  3. Importing model files from multiple locations without caching check
  4. Test suites that re-import models in beforeEach() or before() hooks
  5. Next.js API routes that import models directly instead of checking compiled models
  6. Serverless offline development environment reloading model definitions

How to fix "OverwriteModelError: Cannot overwrite model once compiled"

1Add conditional model export pattern

The safest solution is to check if the model already exists before creating it. Replace your model export with:

javascript
// models/User.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  // ... other fields
});

// Check if model exists, otherwise create it
module.exports = mongoose.models.User || mongoose.model('User', userSchema);

For TypeScript/ES modules:

typescript
// models/User.ts
import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
});

export default mongoose.models.User || mongoose.model('User', userSchema);

This pattern checks mongoose.models.User first and only creates the model if it doesn't exist.

2Ensure single model definition file

Make sure each model is defined and exported in exactly one file. Avoid duplicating model definitions across multiple files.

Good structure:

bash
models/
  ├── User.js
  ├── Post.js
  └── Comment.js

Import models consistently:

javascript
// Always import from the same location
const User = require('./models/User');
const Post = require('./models/Post');

Node.js caches required modules, so importing the same file multiple times will return the cached export.

3Fix test suite model imports

If you're getting this error in tests, avoid re-importing models in test hooks. Instead, import once at the top of the test file:

Before (causes error):

javascript
describe('User tests', () => {
  let User;

  beforeEach(() => {
    // DON'T: This re-imports and tries to recompile the model
    User = require('../models/User');
  });
});

After (fixed):

javascript
const User = require('../models/User'); // Import once at top

describe('User tests', () => {
  beforeEach(async () => {
    // Just clear data, don't re-import model
    await User.deleteMany({});
  });
});
4Clear Mongoose connection in tests (if needed)

If you need to completely reset Mongoose between test suites, properly disconnect and clear models:

javascript
// test/setup.js or afterAll hook
afterAll(async () => {
  // Clear all models from Mongoose registry
  mongoose.connection.models = {};

  // Close connection
  await mongoose.disconnect();
});

Or use Mongoose's deleteModel() method:

javascript
// Clear specific model
mongoose.deleteModel('User');

// Then you can safely recompile
const User = mongoose.model('User', userSchema);

Advanced notes

For Next.js applications: This error is extremely common in Next.js API routes because each API route is treated as a serverless function that may be reloaded during development. Always use the conditional export pattern (mongoose.models.ModelName || mongoose.model(...)) in Next.js projects.

Using separate connections: If you genuinely need multiple model registrations (rare), create separate Mongoose connections:

javascript
const conn1 = mongoose.createConnection('mongodb://localhost/db1');
const conn2 = mongoose.createConnection('mongodb://localhost/db2');

const User1 = conn1.model('User', userSchema);
const User2 = conn2.model('User', userSchema); // Different connection, no conflict

TypeScript with Typegoose: When using Typegoose, use getModelForClass() with the conditional pattern:

typescript
import { getModelForClass } from '@typegoose/typegoose';

export const UserModel = mongoose.models.User || getModelForClass(User);

Development vs Production: This error is more common in development due to hot-reloading. In production, models are typically loaded once during application startup, so the issue rarely occurs. However, serverless environments can trigger the same behavior in production if not handled correctly.

Frequently asked questions

What does "OverwriteModelError: Cannot overwrite model once compiled" mean?
This error is thrown by Mongoose (the MongoDB ODM) when you attempt to compile a model that has already been registered in the Mongoose instance. models, and once a model is compiled with a specific name, it cannot be overwritten without clearing the registry first. The error typically occurs because Mongoose is designed to prevent accidental model redefinition, which could lead to inconsistent schema definitions and unpredictable behavior.
How do I fix "OverwriteModelError: Cannot overwrite model once compiled"?
This Mongoose error occurs when trying to register a model with the same name multiple times. It commonly happens in development environments with hot-reloading, serverless functions, or test suites that re-import model files.
What causes "OverwriteModelError: Cannot overwrite model once compiled"?
Calling mongoose.model() multiple times with the same model name Hot module replacement (HMR) in development causing model files to reload Importing model files from multiple locations without caching check
Is the "OverwriteModelError: Cannot overwrite model once compiled" error serious?
It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.

Official resources & further reading