211

Not Sure what I'm doing wrong, here is my check.js

var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));

var a1= db.once('open',function(){
var user = mongoose.model('users',{ 
       name:String,
       email:String,
       password:String,
       phone:Number,
      _enabled:Boolean
     });

user.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere })
    });

and here is my insert.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')

var user = mongoose.model('users',{
     name:String,
     email:String,
     password: String,
     phone:Number,
     _enabled:Boolean
   });

var new_user = new user({
     name:req.body.name,
     email: req.body.email,
     password: req.body.password,
     phone: req.body.phone,
     _enabled:false
   });

new_user.save(function(err){
    if(err) console.log(err); 
   });

Whenever I'm trying to run check.js, I'm getting this error

Cannot overwrite 'users' model once compiled.

I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.

Here is what I'm getting from the client interface of my MongoDB:

MongoDB shell version: 2.4.6 connecting to: test 
> use event-db 
  switched to db event-db 
> db.users.find() 
  { "_id" : ObjectId("52457d8718f83293205aaa95"), 
    "name" : "MyName", 
    "email" : "[email protected]", 
    "password" : "myPassword", 
    "phone" : 900001123, 
    "_enable" : true 
  } 
>
2
  • Here is what I'm getting from the client interface of my MongoDB: MongoDB shell version: 2.4.6 connecting to: test > use event-db switched to db event-db > db.users.find() { "_id" : ObjectId("52457d8718f83293205aaa95"), "name" : "MyName", "email" : "[email protected]", "password" : "myPassword", "phone" : 900001123, "_enable" : true } > Sep 27, 2013 at 12:46
  • sometimes it's just a stupid error we makes, in my case :the exports was like{userModel:model("user",userSchema)...so every time he access the file it recreate model and trigger the error... so instead of exporting like this make a constant "const userModel=model("user",userSchema) then export it like module.exports = { userModel }
    – Bakaji
    Jul 1, 2021 at 10:10

51 Answers 51

306

Another reason you might get this error is if you use the same model in different files but your require path has a different case.

For example, in my situation I had require('./models/User') in one file, and then in another file where I needed access to the User model, I had require('./models/user').

I guess the lookup for modules & mongoose is treating it as a different file. Once I made sure the case matched in both it was no longer an issue.

3
  • 15
    That's very tricky problem indeed - I think it is OS specific (it should happen only on Mac and Windows as the FS ignores the case). I had this problem, but luckily saw your answer :) Thanks a lot Jonnie! Dec 23, 2015 at 13:11
  • 9
    this problem happens in my OS X system.
    – lutaoact
    Feb 18, 2016 at 13:05
  • This was the same for me. All hail OS X and its (case insesitive by default) file system Nov 24, 2016 at 22:09
171

The error is occurring because you already have a schema defined, and then you are defining the schema again. Generally what you should do is instantiate the schema once, and then have a global object call it when it needs it.

For example:

user_model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
   name:String,
   email:String,
   password:String,
   phone:Number,
   _enabled:Boolean
});
module.exports = mongoose.model('users', userSchema);          

check.js

var mongoose = require('mongoose');
var User = require('./user_model.js');

var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
  User.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere 
  })
});

insert.js

var mongoose = require('mongoose');
var User = require('./user_model.js');

mongoose.connect('mongodb://localhost/event-db');
var new_user = new User({
    name:req.body.name
  , email: req.body.email
  , password: req.body.password
  , phone: req.body.phone
  , _enabled:false 
});
new_user.save(function(err){
  if(err) console.log(err); 
});
5
  • 101
    Avoid exporting/requiring models — if any have refs to other models this can lead to a dependency nightmare. Use var User = mongoose.model('user') instead of require.
    – wprl
    Sep 27, 2013 at 14:30
  • 1
    It can actually be useful to change a Schema after defining for testing schema migration code. Jan 28, 2014 at 18:21
  • 3
    @wprl can you please explain it further? why would requiring it create problem?
    – varuog
    Oct 15, 2018 at 22:15
  • 3
    This answer is misleading. The fact is that if there only one mongoDB server instance and more Databases, if you define in another app the a database already taken then you got such error. Simply as that Dec 16, 2019 at 17:28
  • This doesn't make much sense in that import would only be called one time in theory. Calling it again wouldn't execute the given create script but should simply return what was assigned on the exports. Sep 8, 2022 at 18:48
141

I had this issue while 'watching' tests. When the tests were edited, the watch re-ran the tests, but they failed due to this very reason.

I fixed it by checking if the model exists then use it, else create it.

import mongoose from 'mongoose';
import user from './schemas/user';

export const User = mongoose.models.User || mongoose.model('User', user);
11
  • 3
    to bad mongoose.models does not exists, at least in recent versions
    – Pedro Luz
    Apr 25, 2018 at 10:58
  • 3
    I had the same issue but fixed it with clearing all models before all tests: for (let model in mongoose.models) delete mongoose.models[model]
    – E. Sundin
    Jun 17, 2018 at 21:02
  • 4
    Using this in the latest release of Mongoose and it seems to work great! Jan 28, 2021 at 19:28
  • 2
    this worked for me.
    – Cuado
    Oct 19, 2021 at 16:16
  • 3
    This answer helped me to fix the error when i made changes in my code an then the hmr reloads the page and the error error - OverwriteModelError: Cannot overwrite Brand` model once compiled.` appears.
    – Yersskit
    Jan 29, 2022 at 1:53
67

I had this issue while unit testing.

The first time you call the model creation function, mongoose stores the model under the key you provide (e.g. 'users'). If you call the model creation function with the same key more than once, mongoose won't let you overwrite the existing model.

You can check if the model already exists in mongoose with:

let users = mongoose.model('users')

This will throw an error if the model does not exist, so you can wrap it in a try/catch in order to either get the model, or create it:

let users
try {
  users = mongoose.model('users')
} catch (error) {
  users = mongoose.model('users', <UsersSchema...>)
}
4
  • 1
    +1 I was having the same issue where I needed to setup some configuration for a plugin before I could define my schema. This did not play well with mocha at all and in the end I gave up and just went with this try catch approach Oct 10, 2016 at 20:54
  • I'm using the same but the other way around, that's wicked: try exports.getModel = ()-> mongoose.model('User', userSchema) catch err exports.getModel = ()-> mongoose.model('User')
    – Andi Giga
    Jun 2, 2017 at 8:34
  • 1
    Thank you good sir, wasted 5+ hours on this problem. I was working with serverless unlike node server which I'm used to.
    – mxdi9i7
    Feb 13, 2019 at 22:46
  • 2
    Update for 2021: export default mongoose.models["user"] ?? mongoose.model("user", schema)
    – kshksdrt
    Feb 28, 2021 at 14:04
54

If you are using Serverless offline and don't want to use --skipCacheInvalidation, you can very well use:

module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);
6
  • You also must use this if you're importing one model inside another, even with --skipCacheInvalidation
    – Powderham
    Apr 20, 2019 at 11:39
  • 11
    This is the exact answer I was looking for, for use in Next.js. I wish this was higher up on the page! May 15, 2020 at 6:08
  • 1
    but the problem is that Typescript will not detect models.User as defined in Interface, it will fallback to any
    – rony
    Nov 17, 2020 at 11:15
  • 3
    I never had this problem until it happened when I tried mongoose in Next.js This solution is working for me, thanks! I think it is happening in Next.js because of how their development mode is configured. Maybe Next.js team can improve this...
    – Shaman
    Jan 12, 2021 at 6:41
  • 1
    @rony I had this issue with TypeScript and solved it with: const getModel = () => model("User", UserSchema); module.exports = (models.User || getModel()) as ReturnType<typeof getModel>;
    – bozdoz
    May 27, 2021 at 4:14
26

I have been experiencing this issue & it was not because of the schema definitions but rather of serverless offline mode - I just managed to resolve it with this:

serverless offline --skipCacheInvalidation

Which is mentioned here https://github.com/dherault/serverless-offline/issues/258

Hopefully that helps someone else who is building their project on serverless and running offline mode.

3
  • 6
    I found it annoying to skip cache invalidation, constant reloads, instead this works module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema); May 11, 2018 at 4:19
  • This was super useful and worked well for me until I was importing a model again inside another model. To prevent this error we need to use the solution by @asked_io.
    – Powderham
    Apr 20, 2019 at 11:37
  • tried @Moosecunture solution but giving an error. but It worked. Thanks. May 9, 2021 at 9:34
20

If you made it here it is possible that you had the same problem i did. My issue was that i was defining another model with the same name. I called my gallery and my file model "File". Darn you copy and paste!

0
17

I solved this by adding

mongoose.models = {}

before the line :

mongoose.model(<MODEL_NAME>, <MODEL_SCHEMA>)

Hope it solves your problem

4
  • This was what I did and it fixed it. mongoose.connection.models = {};
    – Fortune
    Aug 28, 2019 at 22:55
  • Typescript throws an error cannot assign to models because it is read only property
    – bhavesh
    Sep 12, 2021 at 7:39
  • 1
    won't this clear all your previously defined models?!
    – Ali80
    May 23, 2022 at 15:55
  • Yeah... Don't do this. It'll clear all of the models Mongoose has cached so far, and continually recreate and cache the model for every request your server receives. This is bad, both in terms of performance, and in troubleshooting. Use one of these instead.
    – Jack_Hu
    May 8, 2023 at 18:57
14

Click here! Official example. Most important! thing is to export like this

export default mongoose.models.Item || mongoose.model('Item', itemsSchema)
1
  • this seems to just export a vanilla model, and i lose all the custom methods I had attached to my User model eg Property 'findOrCreateDiscordUser' does not exist on type 'Model<any, {}, {}>'.
    – dcsan
    Nov 10, 2021 at 14:56
13

This happened to me when I write like this:

import User from '../myuser/User.js';

However, the true path is '../myUser/User.js'

1
  • Mixing case of schema paths when importing seems to cause this problem - check that all files importing the schema use the same case. Sep 23, 2017 at 4:49
8

To Solve this check if the model exists before to do the creation:

if (!mongoose.models[entityDBName]) {
  return mongoose.model(entityDBName, entitySchema);
}
else {
  return mongoose.models[entityDBName];
}
6

Here is one more reason why this can happen. Perhaps this can help someone else. Notice the difference, Members vs Member. They must be the same...

export default mongoose.models.Members || mongoose.model('Member', FamilySchema)

Change to:

export default mongoose.models.Member || mongoose.model('Member', FamilySchema)
1
  • thanks, this helps especially with "i think" the hot reload of the development server, which was my case. Apr 6, 2021 at 16:07
5

I know there is an accepted solution but I feel that the current solution results in a lot of boilerplate just so that you can test Models. My solution is essentially to take you model and place it inside of a function resulting in returning the new Model if the Model has not been registered but returning the existing Model if it has.

function getDemo () {
  // Create your Schema
  const DemoSchema = new mongoose.Schema({
    name: String,
    email: String
  }, {
    collection: 'demo'
  })
  // Check to see if the model has been registered with mongoose
  // if it exists return that model
  if (mongoose.models && mongoose.models.Demo) return mongoose.models.Demo
  // if no current model exists register and return new model
  return mongoose.model('Demo', DemoSchema)
}

export const Demo = getDemo()

Opening and closing connections all over the place is frustrating and does not compress well.

This way if I were to require the model two different places or more specifically in my tests I would not get errors and all the correct information is being returned.

5

This may give a hit for some, but I got the error as well and realized that I just misspelled the user model on importing.

wrong: const User = require('./UserModel'); correct: const User = require('./userModel');

Unbelievable but consider it.

1
  • Seems like a possible bug in node Sep 11, 2020 at 22:00
4

What you can also do is at your export, make sure to export an existing instance if one exists.

Typescript solution:

import { Schema, Document, model, models } from 'mongoose';

const UserSchema: Schema = new Schema({
    name: {
        type: String
    }
});

export interface IUser extends Document {
    name: string
}

export default models.Users || model<IUser>('Users', UserSchema);
1
  • 1
    We can also set this way: export default model<IUser>('Users', UserSchema,{overwriteModels:true}); Jun 20, 2022 at 19:54
4

I faced this issue using Next.js and TypeScript. The top answers made it such that typings would not work.

This is what works for me:

const { Schema } = mongoose

export interface IUser {
  name: string
  email: string
}

const UserSchema = new Schema<IUser>({
  name: { type: String, required: true },
  email: { type: String, required: true },
})

const UserModel = () => mongoose.model<IUser>('User', UserSchema)

export default (mongoose.models.User || UserModel()) as ReturnType<
  typeof UserModel
>
0
3

This problem might occur if you define 2 different schema's with same Collection name

3
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

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

// Trying to get the existing model to avoid OverwriteModelError
module.exports = mongoose.model("user") || mongoose.model('user', userSchema);
2

You can easily solve this by doing

delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);
1
  • useful for dynamic schema case
    – May'Habit
    Jun 28, 2022 at 3:42
2

There is another way to throw this error.

Keep in mind that the path to the model is case sensitive.

In this similar example involving the "Category" model, the error was thrown under these conditions:

1) The require statement was mentioned in two files: ..category.js and ..index.js 2) I the first, the case was correct, in the second file it was not as follows:

category.js

enter image description here

index.js

enter image description here

2

I solved this issue by doing this

// Created Schema - Users
// models/Users.js
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

export const userSchema = new Schema({
  // ...
});

Then in other files

// Another file
// index.js
import { userSchema } from "../models/Users";
const conn = mongoose.createConnection(process.env.CONNECTION_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
conn.models = {};
const Users = conn.model("Users", userSchema);
const results = await Users.find({});

Better Solution

let User;
try {
  User = mongoose.model("User");
} catch {
  User = mongoose.model("User", userSchema);
}

I hope this helps...

1
  • 1
    No clue why it's so difficult to provide explanations. Imagine the time you waste as everyone reads through your code.
    – danefondo
    Aug 10, 2020 at 21:48
2

I faced the same Issue with NextJS and MongoDB atlas. I had a models folder with the model of session stored, but the problem was not that I defined the Schema twice.

  1. Make sure the Collection is empty and does not have a previous Document
  2. If it does, then Simply declare a Model without Schema, like this:
const Session = mongoose.model("user_session_collection")
  1. You can delete the previous records or backup them, create the schema and then apply query on the database.

Hope it helped

2

Below is the full solution to similar problem when using Mongoose with Pagination in combination with Nuxt and Typescript:

import {model, models, Schema, PaginateModel, Document } from 'mongoose';

import { default as mongoosePaginate } from 'mongoose-paginate-v2';

export interface IUser extends Document {
    name: string;
}

const UserSchema: Schema = new Schema({
    name: String
});

UserSchema.plugin(mongoosePaginate)

interface User<T extends Document> extends PaginateModel<T> {}


const User: User<IUser> = models['User'] as User<IUser> || model<IUser>('User', UserSchema) as User<IUser>;

export default User

tsconfig.json:

{
    "compilerOptions": {
        "target": "ES2018",
        "module": "ESNext",
        "moduleResolution": "Node",
        "lib": ["ESNext", "ESNext.AsyncIterable", "DOM"],
        "esModuleInterop": true,
        "allowJs": true,
        "sourceMap": true,
        "strict": true,
        "noEmit": true,
        "baseUrl": ".",
        "paths": {
            "~/*": ["./*"],
            "@/*": ["./*"]
        },
        "types": ["@types/node", "@nuxt/types"]
    },
    "exclude": ["node_modules"]
}

To make pagination working you will also need to install @types/mongoose-paginate-v2


The above solution should also deal with problems related to hot reloading with Nuxt (ServerMiddleware errors) and pagination plugin registration.

2

A solution that worked for me was just to check if an instance of the model exists before creating and exporting the model.

import mongoose from "mongoose";
const { Schema } = mongoose;
const mongoosePaginate = require("mongoose-paginate");

const articleSchema = new Schema({
  title: String, // String is shorthand for {type: String}
  summary: String,
  data: String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  published: { type: Boolean, default: true },
  tags: [{ name: String }],
  category: String,
  _id: String,
});


const Post = mongoose.models.Post ? mongoose.models.Post : mongoose.model("Post",articleSchema);

export default Post;

1
  • This solution works but also arrises another error. This change makes expressions like .create(), .findById and ... not callable. I have answered with a fix to it 👍!
    – Haneen
    Sep 29, 2022 at 16:49
2

If you have overWrite problem. You should make check the models.

let User

if (mongoose.models.User) {
    User = mongoose.model('User')
} else {
    User = mongoose.model('User', userSchema)
}
2

I have the same issue but when i check my code then I figure out that there is a typo in code

Error Code 👇

import mongoose from "mongoose";

const contentSchema = new mongoose.Schema({
    content: {
        type: String,
        required: true
    },
}, { timestamps: true })

const ContentPost = mongoose.Schema.contents || mongoose.model("contents", contentSchema);

export default ContentPost;

Error Free Code 👇

import mongoose from "mongoose";

const contentSchema = new mongoose.Schema({
    content: {
        type: String,
        required: true
    },
}, { timestamps: true })

const ContentPost = mongoose.models.contents || mongoose.model("contents", contentSchema);

export default ContentPost;

I write the Schema in place of of model const ContentPost = mongoose.Schema.contents || mongoose.model("contents", contentSchema);

1

The schema definition should be unique for a collection, it should not be more then one schema for a collection.

1
If you want to overwrite the existing class for different collection using typescript
then you have to inherit the existing class from different class.

export class User extends Typegoose{
  @prop
  username?:string
  password?:string
}


export class newUser extends User{
    constructor() {
        super();
    }
}

export const UserModel = new User ().getModelForClass(User , { schemaOptions: { collection: "collection1" } });

export const newUserModel = new newUser ().getModelForClass(newUser , { schemaOptions: { collection: "collection2" } });
1

I had the same problem, reason was I defined schema an model in a JS function, they should be defined globally in a node module, not in a function.

1

just export like this exports.User = mongoose.models.User || mongoose.model('User', userSchema);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.