iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦔

How to fix "Cannot overwrite 'Model' model once compiled" error in Mongoose

に公開

After defining a model with mongoose, you may encounter the following error when hot-reloading or performing similar actions:

Cannot overwrite 'Model' model once compiled. 

The model is defined as follows:

import mongoose, { Schema, Document, Model } from 'mongoose'

export interface UserDoc extends Document, {
  username: string
  email: string
  password: string
}

const userSchema: Schema = new Schema(
  {
    username: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
  }
)

interface UserModel extends Model<UserDoc> {}

export default mongoose.model<UserDoc, UserModel>('User', userSchema)

In mongoose, you cannot create an instance more than once using mongoose.model() with the same schema.

You can resolve the error by modifying it as follows:

- import mongoose, { Schema, Document, Model } from 'mongoose'
+ import mongoose, { Schema, Document, Model, models } from 'mongoose'

export interface UserDoc extends Document, {
  username: string
  email: string
  password: string
}

const userSchema: Schema = new Schema(
  {
    username: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
  }
)

interface UserModel extends Model<UserDoc> {}

- export default mongoose.model<UserDoc, UserModel>('User', userSchema)
+ export default models.User
+   ? (models.User as UserModel)
+   : mongoose.model<UserDoc, UserModel>('User', userSchema)

In mongoose, models allows you to retrieve already registered models by using the model name as a key.

If it already exists in models, you can resolve the error caused by re-registering the same model by exporting that existing one.

When using TypeScript, models registered in models may not have the correct type if you have added things like statics to the model, so you will likely need to use type assertion.

If it is not registered in models, create and export the model as usual.

GitHubで編集を提案

Discussion