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)

Most upvoted comments

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 User model was registered or not.

let modelName = ...
let schema = ...
const Model = mongoose.models[modelName] || mongoose.model(modelName, schema);

export default Model;

fixed by v2.14.4 @kamran-12 now you should be able to normally use serverMiddleware without HMR issues with mongoose 😃

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'}] to serverMiddleware: [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.

Alternatively before fix for mongoose, you can use concurrently to run API standalone and make requests from UI to it. (can provide more detailed info how to do)

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

You can avoid mongoose error by checking models to see if User model was registered or not.

@farnabaz I guess this will cause not applying schema changes.

One workaround is doing full reload for server by directly importing serveriMiddleware like this:

export default {
  serverMiddleware: [
    require('./api')
  ]
}

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