200

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" : "myemail@me.com", 
    "password" : "myPassword", 
    "phone" : 900001123, 
    "_enable" : true 
  } 
>
devprashant
  • 1,285
  • 1
  • 13
  • 23
Anathema.Imbued
  • 3,271
  • 4
  • 17
  • 18
  • 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" : "myemail@me.com", "password" : "myPassword", "phone" : 900001123, "_enable" : true } > – Anathema.Imbued Sep 27 '13 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 01 '21 at 10:10

47 Answers47

302

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.

Asker
  • 1,299
  • 2
  • 14
  • 31
jonnie
  • 12,260
  • 16
  • 54
  • 91
168

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); 
});
thtsigma
  • 4,878
  • 2
  • 28
  • 29
  • 98
    Avoid exporting/requiring models — if any have `ref`s to other models this can lead to a dependency nightmare. Use `var User = mongoose.model('user')` instead of `require`. – wprl Sep 27 '13 at 14:30
  • 1
    It can actually be useful to change a Schema after defining for testing schema migration code. – Igor Soarez Jan 28 '14 at 18:21
  • 3
    @wprl can you please explain it further? why would requiring it create problem? – varuog Oct 15 '18 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 – Carmine Tambascia Dec 16 '19 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. – Jakub Keller Sep 08 '22 at 18:48
126

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);
ZephDavies
  • 3,964
  • 2
  • 14
  • 19
  • 1
    This worked for me. I had changed the `module.export = User` to `export defaults User`. I also had `refs` to User from other models. I am unsure why changing from `module.exports` to `export default` brought this issue. Nevertheless, this answer seems to have fixed it. – runios Feb 26 '18 at 08:11
  • 3
    to bad `mongoose.models` does not exists, at least in recent versions – Pedro Luz Apr 25 '18 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 '18 at 21:02
  • My test script looks like so: `"test": "NODE_ENV=test mocha --file mocha.config.js --watch"` and in that config js file I have a `before()` and `after()` to handle setup and teardown. @E.Sundin provided the perfect solution here, and it works like a charm. Thank you! – Brandon Aaskov Nov 20 '19 at 22:49
  • 4
    Using this in the latest release of Mongoose and it seems to work great! – Dana Woodman Jan 28 '21 at 19:28
  • 1
    this worked for me. – Cuado Oct 19 '21 at 16:16
  • 1
    This is the badarse answer - works as a charm ! – Hairi Dec 03 '21 at 14:59
  • 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 '22 at 01:53
  • 1
    This worked well for me in the latest version of Mongoose. Using it on Next JS with TypeScript. Worked like a charm. – josealvarez97 Apr 12 '23 at 00:14
  • This is clean and easy. Thanks – ganjim Aug 09 '23 at 23:04
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...>)
}
BJ Anderson
  • 1,096
  • 9
  • 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 – Victor Parmar Oct 10 '16 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 02 '17 at 08: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 '19 at 22:46
  • 2
    Update for 2021: `export default mongoose.models["user"] ?? mongoose.model("user", schema)` – kshksdrt Feb 28 '21 at 14:04
53

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);
Julian
  • 8,808
  • 8
  • 51
  • 90
  • You also must use this if you're importing one model inside another, even with `--skipCacheInvalidation` – Powderham Apr 20 '19 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! – Brendan Nee May 15 '20 at 06: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 '20 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 '21 at 06:41
  • @rony I had this issue with TypeScript and solved it with: const getModel = () => model("User", UserSchema); module.exports = (models.User || getModel()) as ReturnType; – bozdoz May 27 '21 at 04:14
  • This worked well for me in Next JS (TypeScript). – josealvarez97 Apr 12 '23 at 00:16
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.

munyah
  • 281
  • 3
  • 4
  • 6
    I found it annoying to skip cache invalidation, constant reloads, instead this works `module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);` – Will Bowman May 11 '18 at 04: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 '19 at 11:37
  • tried @Moosecunture solution but giving an error. but It worked. Thanks. – Sugam Malviya May 09 '21 at 09: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!

James Harrington
  • 3,138
  • 30
  • 32
17

I solved this by adding

mongoose.models = {}

before the line :

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

Hope it solves your problem

Toufiq
  • 1,096
  • 12
  • 16
  • This was what I did and it fixed it. `mongoose.connection.models = {};` – Fortune Aug 28 '19 at 22:55
  • Typescript throws an error `cannot assign to models because it is read only property` – bhavesh Sep 12 '21 at 07:39
  • 1
    won't this clear all your previously defined models?! – Ali80 May 23 '22 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](https://stackoverflow.com/a/69356199/1682790) [of](https://stackoverflow.com/a/38143030/1682790) [these](https://stackoverflow.com/a/51351095/1682790) instead. – Jack_Hu May 08 '23 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)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Rishabh
  • 151
  • 1
  • 3
  • 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'.` – dcsan Nov 10 '21 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'

ip192
  • 149
  • 1
  • 8
  • Mixing case of schema paths when importing seems to cause this problem - check that all files importing the schema use the same case. – Andrew Cupper Sep 23 '17 at 04:49
7

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];
}
RyanZim
  • 6,609
  • 1
  • 27
  • 43
Alpha BA
  • 301
  • 3
  • 4
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.

Justin Herrera
  • 526
  • 4
  • 11
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);
Mike K
  • 7,621
  • 14
  • 60
  • 120
4

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)
Jack
  • 49
  • 1
  • 3
3

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

3

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
>
Mans
  • 2,953
  • 2
  • 23
  • 32
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);
ABHIJEET KHIRE
  • 2,037
  • 17
  • 10
2

You can easily solve this by doing

delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);
Shyam
  • 633
  • 7
  • 13
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

MEDZ
  • 2,227
  • 2
  • 14
  • 18
Tim
  • 21
  • 3
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
    No clue why it's so difficult to provide explanations. Imagine the time you waste as everyone reads through your code. – danefondo Aug 10 '20 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

DevMayukh
  • 185
  • 7
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.

Jakub A Suplicki
  • 4,586
  • 1
  • 23
  • 31
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;

The Codepreneur
  • 236
  • 3
  • 12
  • 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 Mahdin Sep 29 '22 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)
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
lestonz
  • 149
  • 4
1

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

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
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" } });
Rohit Jangid
  • 2,291
  • 1
  • 11
  • 9
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.

Bulent Balci
  • 644
  • 5
  • 11
1

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

1

ther are so many good answer but for checking we can do easier job. i mean in most popular answer there is check.js ,our guy made it so much complicated ,i suggest:

function connectToDB() {
  if (mongoose.connection.readyState === 1) {
    console.log("already connected");
    return;
  }
  mongoose.connect(
    process.env.MONGODB_URL,
    {
      useCreateIndex: true,
      useFindAndModify: false,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
    (err) => {
      if (err) throw err;
      console.log("DB connected");
    },
  );
}

readyState== 1 means connected
so does not try to connect again
so you won't get the error
i think it because of connecting while it is connected
it is another way of connecting to db

afshar003
  • 765
  • 6
  • 6
1

Make sure you are not using the same model name for two different schemas.

Example:

// course model
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
    course: {
        type: String,
        required: true,
    },
    course_category: {
        type: String,
        required: true,
    }
});
module.exports = mongoose.model("course", courseSchema);

// student model
const mongoose = require("mongoose");
const studentSchema = new mongoose.Schema({
    first_name: {
        type: String,
        required: true,
    },
    last_name: {
        type: String,
        required: true,
    }
});
module.exports = mongoose.model("course", studentSchema);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
1

As per the answer: https://stackoverflow.com/a/34291140/17708926, it fixes this issue partially but also raises another error in the code.

Error

The fix to this problem can be obtained by exporting a new model if it doesn't exist, I know this was the same idea in that answer but now it's implemented differently.

/// ... your schema

const model = mongoose.models.Model || mongoose.model("Model", modelSchema);

export default model;
Haneen Mahdin
  • 1,000
  • 1
  • 7
  • 13
1

fixed my problem for this line

in last

module.exports =
    mongoose.models.Customer || mongoose.model('Customer', customerSchema);
toyota Supra
  • 3,181
  • 4
  • 15
  • 19
0

is because your schema is already, validate before create new schema.

var mongoose = require('mongoose');
module.exports = function () {
var db = require("../libs/db-connection")();
//schema de mongoose
var Schema = require("mongoose").Schema;

var Task = Schema({
    field1: String,
    field2: String,
    field3: Number,
    field4: Boolean,
    field5: Date
})

if(mongoose.models && mongoose.models.tasks) return mongoose.models.tasks;

return mongoose.model('tasks', Task);
0

I have a situation where I have to create the model dynamically with each request and because of that I received this error, however, what I used to fix it is using deleteModel method like the following:

var contentType = 'Product'

var contentSchema = new mongoose.Schema(schema, virtuals);

var model = mongoose.model(contentType, contentSchema);

mongoose.deleteModel(contentType);

I hope this could help anybody.

Engr.MTH
  • 1,002
  • 1
  • 11
  • 23
0
The reason of this issue is: 

you given the model name "users" in the line 
<<<var user = mongoose.model('users' {>>> in check.js file

and again the same model name you are giving in the insert file
<<< var user = mongoose.model('users',{ >>> in insert.js

This "users" name shouldn't be same when you declare a model that should be different 
in a same project.
Rohit Jangid
  • 2,291
  • 1
  • 11
  • 9
0

For all people ending here because of a codebase with a mix of Typegoose and Mongoose :

Create a db connection for each one :

Mongoose :

module.exports = db_mongoose.model("Car", CarSchema);

Typegoose :

db_typegoose.model("Car", CarModel.schema, "cars");
LucasBordeau
  • 1,348
  • 2
  • 11
  • 13
0

I just have a mistake copy pasting. In one line I had same name that in other model (Ad model):

const Admin = mongoose.model('Ad', adminSchema);

Correct is:

const Admin = mongoose.model('Admin', adminSchema);

By the way, if someone have "auto-save", and use index for queries like:

**adSchema**.index({title:"text", description:"text", phone:"text", reference:"text"})

It has to delete index, and rewrite for correct model:

**adminSchema**.index({title:"text", description:"text", phone:"text", reference:"text"})
titoih
  • 522
  • 6
  • 11
0

Since this issue happened because calling model another time. Work around to this issue by wrapping your model code in try catch block. typescript code is like this -

         Import {Schema, model} from 'mongoose';
         export function user(){
              try{
                   return model('user', new Schema ({
                            FirstName: String,
                            Last name: String
                     }));
              }
             catch{
                   return model('user');
              }
         }

Similarly you can write code in js too.

AKP
  • 32
  • 4
0

Adding this line will 100% solve your error.

mongoose.models = {}
cigien
  • 57,834
  • 11
  • 73
  • 112
  • 2
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 28 '21 at 19:33
0

If you are using Serverless offline one of these should do the trick

--skipCacheInvalidation

or

--useSeparateProcesses

especially this current one

--useChildProcesses
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0
var user = mongoose.model('users', {});

Here, in both places, you have used 'users' which is identical so it's a conflict and therefore one cannot overwrite another. To fix this, change them.

0
In my case, i had file structure like this
Modules
-> User
   ->controllers
   ->models
      ->user.model.js
      ->userDetails.model.js
   ->Repository
      ->user.repository.js
      ->userdetails.repository.js
-> Posts
   // same as model

In my repository folder I referenced model like so

      const User = require("../models/user.model") 

but this yelled at me.
All I did to solve this was give a reference of 

    const User = require("../../User/models/user.model")

This solved the problem.. 
happy Hacking
0
mongoose.models = {}

THIS Solution is solved my problem

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 14 '23 at 14:53
  • Hi, there is an already accepted answer, many years ago. Are you sure that your solution works in the original contest? – pierpy Apr 14 '23 at 15:52
0

if the error still persists, add this line to your code inside your models/[your_model].js

delete mongoose.connection.models['your_model'];

This will remove the Product model from the Mongoose model cache, allowing you to redefine it.

Nean
  • 1
-1

You are using mongoose.model with the same variable name "user" in check.js and insert.js.

David Khan
  • 21
  • 4
-3

If you are working with expressjs, you may need to move your model definition outside app.get() so it's only called once when the script is instantiated.

Elesin Olalekan Fuad
  • 3,235
  • 1
  • 14
  • 10
  • this does not make sense, mongoose models are only defined once unless there is an issue with the naming (e.g. case) , once it is first called it is initialised, future requires should just get the instance and not reinstantiate it – jonnie Jan 27 '16 at 19:12
  • This not a solution. – Prathamesh More Apr 13 '20 at 15:31