Mongoose HMR Safety in KickJS: The One-Liner That Prevents OverwriteModelError
Mongoose HMR Safety: The One-Liner That Prevents OverwriteModelError If you have ever used Mongoose with Vite's dev server (or any HMR-capable bundler), you have seen this error: OverwriteModelErro...

Source: DEV Community
Mongoose HMR Safety: The One-Liner That Prevents OverwriteModelError If you have ever used Mongoose with Vite's dev server (or any HMR-capable bundler), you have seen this error: OverwriteModelError: Cannot overwrite `User` model once compiled. It crashes your dev server. It requires a full restart. It happens every time you save a file that is anywhere in the import chain of a schema file. And it is completely preventable with a single line of code. I am going to explain why this happens, show the fix, and then cover the other HMR landmines I stepped on while building Vibed -- a task management backend running on KickJS (which uses Vite under the hood for development). Why It Happens Mongoose maintains a global registry of models. When you call mongoose.model('User', userSchema), it compiles the schema and stores the resulting model in mongoose.models.User. Call it again with the same name, and Mongoose throws OverwriteModelError. In a traditional Node.js setup with ts-node or plain n