Cannot overwrite model once compiled Mongoose
Asked Answered
F

51

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 
  } 
>
Fifi answered 27/9, 2013 at 12:41 Comment(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 } >Fifi
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 }Cypriot
G
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); 
});
Gregg answered 27/9, 2013 at 13:24 Comment(5)
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.Rawhide
It can actually be useful to change a Schema after defining for testing schema migration code.Tameshatamez
@Rawhide can you please explain it further? why would requiring it create problem?Janettjanetta
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 thatHarkness
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.Rowdyism
C
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.

Canto answered 15/12, 2015 at 13:59 Comment(3)
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!Beckmann
this problem happens in my OS X system.Heterogony
This was the same for me. All hail OS X and its (case insesitive by default) file systemHesychast
G
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); 
});
Gregg answered 27/9, 2013 at 13:24 Comment(5)
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.Rawhide
It can actually be useful to change a Schema after defining for testing schema migration code.Tameshatamez
@Rawhide can you please explain it further? why would requiring it create problem?Janettjanetta
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 thatHarkness
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.Rowdyism
F
142

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);
Fisticuffs answered 3/5, 2017 at 13:18 Comment(12)
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.Therine
to bad mongoose.models does not exists, at least in recent versionsLegge
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]Tangleberry
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!Lynwoodlynx
Using this in the latest release of Mongoose and it seems to work great!Hattie
this worked for me.Lachus
This is the badarse answer - works as a charm !Stadler
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.Galleon
This worked well for me in the latest version of Mongoose. Using it on Next JS with TypeScript. Worked like a charm.Carboloy
This is clean and easy. ThanksMicrocopy
Thanks @Fisticuffs This helped me to fix the same error and to the point.Carthy
This method actually worked for me. But in my case i used export const Users = mongoose.models["Users"] || mongoose.model("Users", usersSchema)Squab
O
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...>)
}
Overrate answered 1/7, 2016 at 10:26 Comment(4)
+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 approachUmbrella
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')Losel
Thank you good sir, wasted 5+ hours on this problem. I was working with serverless unlike node server which I'm used to.Conjunctivitis
Update for 2021: export default mongoose.models["user"] ?? mongoose.model("user", schema)Rellia
S
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);
Seclusion answered 15/7, 2018 at 18:35 Comment(6)
You also must use this if you're importing one model inside another, even with --skipCacheInvalidationMercier
This is the exact answer I was looking for, for use in Next.js. I wish this was higher up on the page!Selfexplanatory
but the problem is that Typescript will not detect models.User as defined in Interface, it will fallback to anyAbyss
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...Brasil
@Abyss I had this issue with TypeScript and solved it with: const getModel = () => model("User", UserSchema); module.exports = (models.User || getModel()) as ReturnType<typeof getModel>;Glissando
This worked well for me in Next JS (TypeScript).Carboloy
M
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.

Mello answered 8/8, 2017 at 16:36 Comment(3)
I found it annoying to skip cache invalidation, constant reloads, instead this works module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);Stichomythia
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.Mercier
tried @Moosecunture solution but giving an error. but It worked. Thanks.Carcass
C
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!

Cletus answered 6/3, 2015 at 3:23 Comment(0)
G
17

I solved this by adding

mongoose.models = {}

before the line :

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

Hope it solves your problem

Gassman answered 27/11, 2018 at 17:33 Comment(4)
This was what I did and it fixed it. mongoose.connection.models = {};Goncourt
Typescript throws an error cannot assign to models because it is read only propertyGenovevagenre
won't this clear all your previously defined models?!Subserve
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.Infelicity
M
14

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

export default mongoose.models.Item || mongoose.model('Item', itemsSchema)
Minimize answered 28/9, 2021 at 5:23 Comment(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, {}, {}>'.Classless
S
13

This happened to me when I write like this:

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

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

Sheathe answered 1/7, 2017 at 6:55 Comment(1)
Mixing case of schema paths when importing seems to cause this problem - check that all files importing the schema use the same case.Countershaft
S
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];
}
Sprague answered 22/6, 2019 at 16:44 Comment(0)
R
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)
Remember answered 9/10, 2020 at 22:29 Comment(1)
thanks, this helps especially with "i think" the hot reload of the development server, which was my case.Emphatic
G
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.

Gage answered 10/4, 2017 at 13:15 Comment(0)
M
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.

Makalu answered 3/9, 2020 at 6:1 Comment(1)
Seems like a possible bug in nodeExternal
V
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);
Vermilion answered 3/9, 2020 at 15:34 Comment(1)
We can also set this way: export default model<IUser>('Users', UserSchema,{overwriteModels:true});Viperine
B
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
>
Blowing answered 5/8, 2021 at 16:17 Comment(0)
S
3

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

Spurling answered 30/1, 2018 at 7:0 Comment(0)
R
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);
Rhinitis answered 15/10, 2021 at 5:44 Comment(0)
P
2

You can easily solve this by doing

delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);
Pinero answered 29/9, 2018 at 17:8 Comment(1)
useful for dynamic schema casePrepositive
D
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

Delate answered 21/1, 2020 at 21:34 Comment(0)
H
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...

Harless answered 30/6, 2020 at 5:10 Comment(1)
No clue why it's so difficult to provide explanations. Imagine the time you waste as everyone reads through your code.Isolation
U
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

Unprintable answered 1/9, 2021 at 14:56 Comment(0)
M
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.

Misesteem answered 1/11, 2021 at 21:19 Comment(0)
R
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;

Ramtil answered 12/6, 2022 at 3:50 Comment(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 👍!Bureaucracy
G
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)
}
Gloriole answered 9/4, 2023 at 2:7 Comment(0)
A
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);

Accepted answered 2/3 at 13:20 Comment(0)
P
1

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

Panthea answered 22/2, 2017 at 5:6 Comment(0)
S
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" } });
Staphylococcus answered 24/6, 2018 at 7:41 Comment(0)
L
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.

Lens answered 6/12, 2019 at 18:39 Comment(0)
A
1

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

Analogous answered 15/12, 2020 at 9:12 Comment(0)
B
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

Backdrop answered 25/12, 2020 at 21:49 Comment(0)
K
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);
Kipton answered 12/2, 2022 at 13:33 Comment(0)
B
1

As per the answer: https://mcmap.net/q/126024/-cannot-overwrite-model-once-compiled-mongoose, 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;
Bureaucracy answered 29/9, 2022 at 16:57 Comment(0)
S
1

mongoose.model('Customer', customerSchema): This creates a Mongoose model named 'Customer' using the 'customerSchema' schema if the 'Customer' model doesn't exist

module.exports =
    mongoose.models.Customer || mongoose.model('Customer', customerSchema);
Silly answered 11/8, 2023 at 21:58 Comment(0)
C
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);
Charlatan answered 6/6, 2018 at 7:7 Comment(0)
C
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.

Caneghem answered 15/11, 2018 at 23:37 Comment(0)
S
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.
Staphylococcus answered 31/5, 2019 at 18:37 Comment(0)
M
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");
Mudd answered 11/9, 2019 at 13:21 Comment(0)
C
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"})
Countryandwestern answered 12/4, 2020 at 18:42 Comment(0)
B
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.

Bigamous answered 28/5, 2020 at 6:4 Comment(0)
C
0

Adding this line will 100% solve your error.

mongoose.models = {}
Crowning answered 28/11, 2021 at 18:40 Comment(1)
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.Tong
P
0

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

--skipCacheInvalidation

or

--useSeparateProcesses

especially this current one

--useChildProcesses
Perk answered 13/5, 2022 at 15:38 Comment(0)
J
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.

Jacobine answered 15/1, 2023 at 20:15 Comment(0)
T
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
Tepper answered 4/4, 2023 at 21:54 Comment(0)
N
0
mongoose.models = {}

THIS Solution is solved my problem

Nahama answered 14/4, 2023 at 8:17 Comment(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.Tong
Hi, there is an already accepted answer, many years ago. Are you sure that your solution works in the original contest?Amalgamate
P
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.

Potation answered 20/4, 2023 at 3:18 Comment(0)
V
0

Make sure you write correct syntax, for eg

Wrong syntax

export default mongoose.model.Users || mongoose.model("Users", UsersSchema);

Right syntax

export default mongoose.models.Users || mongoose.model("Users", UsersSchema);

I have seen many people writes mongoose.model instead of mongoose.models before the OR || operator

Vena answered 28/9, 2023 at 7:51 Comment(0)
L
0

This solution works well, but has the problem that type information of the schema is lost.

export default mongoose.models.Users || mongoose.model("Users", UsersSchema);

so I found this elegant solution.

export default mongoose.models.Users as unknown as null ?? model("Users", UsersSchema)

from here. https://qiita.com/mrin/items/43fb1c703f6f5a0ff56c

Lentil answered 26/10, 2023 at 12:28 Comment(0)
A
0

Deleting the /dist folder did the trick for me after I tried almost every other solution

Amber answered 15/12, 2023 at 21:47 Comment(0)
A
-1

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

Anastomose answered 8/3, 2020 at 8:17 Comment(0)
R
-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.

Ranie answered 20/1, 2016 at 19:16 Comment(2)
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 itCanto
This not a solution.Pedraza

© 2022 - 2024 — McMap. All rights reserved.