nuxt: App crashes on ServerMiddleware hot reload if Mongoose models are used, gives an error like "ServerMiddleware Error: Cannot overwrite User model once compiled"
Versions
- nuxt: v2.14.1
- node: v12.18.3
Reproduction
Use this project to reproduce, you may need to add a working MongoDB database credentials in .env file.
Steps to reproduce
npm install npm run dev (No error at this point yet) Make a change in login.js file Save
What is Expected?
Normal hot reload of servermiddleware as always (like when Mongoose is not used).
What is actually happening?
App crashes with this error:
ERROR ServerMiddleware Error: Cannot overwrite User model once compiled.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 15 (8 by maintainers)
Nodemon restarts the whole server on file change, but Nuxt removes the cache and re-import the file. I believe this is not a bug its nuxt approach to reload files.
Restarting the server on every file change has a great impact on performance.
You can avoid mongoose error by checking models to see if
Usermodel was registered or not.fixed by v2.14.4 @kamran-12 now you should be able to normally use serverMiddleware without HMR issues with mongoose 😃
@danielroe #9456
Why this has been closed? It still persists in nuxt 2.15.7
@pi0 if I understood right, you suggested to replace
serverMiddleware: [{path: '/api', handler: '~/api/index'}]toserverMiddleware: [require('./api')]in nuxt.config.js. It didn’t work. The error didn’t go away. I have said this in the last sentence of my previous comment.That would be helpful.
This issue is both with nuxt HMR and mongoose. Using default connection, it keeps instance in CJS cache and when reloading app, it causes this error
@farnabaz I guess this will cause not applying schema changes.
One workaround is doing full reload for server by directly importing serveriMiddleware like this:
Maybe we can also introduce an option to HMR some node_module dependencies. Currently we don’t clear cache for all
node_modules(src) which is also not configurable but if it is, we can specify mongoose or other HMR incompatible dependencies.This isn’t related to Nuxt, This is mongoose error. When a change occurs and Nuxt reload model files and mongoose models call twice.
Here you can find a fix: https://stackoverflow.com/questions/19051041/cannot-overwrite-model-once-compiled-mongoose