Mongoose Error: Cannot Overwrite Model Once Compiled

Updated: December 28, 2023 By: Guest Contributor Post a comment

The Cannot overwrite model once compiled error in Mongoose with Node.js usually occurs when you try to recompile a Mongoose model using the same name more than once within your application. This often happens in cases where you call mongoose.model for an already defined model or you are importing your models in a way that causes them to be registered multiple times.

Reasons Behind the Error

  • Requiring the model file multiple times: If your model is being required in different parts of your application without proper checks, it can lead to this error.
  • Declaring the same model name: If you accidentally declare multiple models with the same name, Mongoose will throw this error.
  • Reloading the model file: In a development environment with hot-reloading, the model file might get reloaded, causing the models to be recompiled.

Steps to Fix the Error

To resolve this problem, several approaches can be taken:

Method 1: Check for Model Existence before Compiling

const mongoose = require('mongoose');

let myModel;
if (mongoose.models.MyModel) {
  myModel = mongoose.model('MyModel');
} else {
  const MySchema = new mongoose.Schema({ /* schema definition */ });
  myModel = mongoose.model('MyModel', MySchema);
}

Method 2: Use mongoose.model Without Schema to Get the Model

const mongoose = require('mongoose');

const MySchema = new mongoose.Schema({ /* schema definition */ });
mongoose.model('MyModel', MySchema);

// Later in the code
const MyModel = mongoose.model('MyModel');

Method 3: Avoid Duplicate Model Declaration With Module Caching

Make sure you declare and export your model in one file and then require it wherever needed. Node.js caches the required modules, so it will not recompile your model.

// myModel.js
const mongoose = require('mongoose');
const MySchema = new mongoose.Schema({ /* schema definition */ });
module.exports = mongoose.model('MyModel', MySchema);

// otherFile.js
const MyModel = require('./myModel');

Complete Code Example

Here’s how you might structure your model file to avoid the Cannot overwrite model once compiled error:

// myModel.js
const mongoose = require('mongoose');
const MySchema = new mongoose.Schema({
  name: String
  // ... other fields ...
});

const MyModel = mongoose.models.MyModel || mongoose.model('MyModel', MySchema);
module.exports = MyModel;

// app.js or any other file
const MyModel = require('./myModel');

// Now you can use MyModel to create, find, update, or delete documents