0

I am having trouble with require executing my code twice. Working on a standard Express app I build Mongoose Schemas, each in it's own files and export them.

//user.js
const User = mongoose.model('User', userSchema)
module.exports = User

//In other files
const User = require('../models/User')

Now I use this in two places in my application and get an error saying that

Cannot overwrite `User` model once compiled.

So the code above is getting called twice as it is the only code right now creating a model. However I would expect Node to only execute it once since it is required in my code.

The really strange part is that checking out an earlier version from Git I get the same error and people working with me on this get the same error. So I have no more ideas where to look for solutions.

H_end-rik
  • 551
  • 1
  • 6
  • 19

2 Answers2

2

Found the solution now.

Turns out I required the module once as models/user and once as model/User which in the cache of require creates two separate modules.

There have been many discussion about this:

one issue

another issue

old PR

It seems that this is due to Windows resolving paths case insensitive while other systems resolve paths case sensitive and node therefore doing it sensitive.

And a new module of'cause gets executed. Simply requiring is both times spelled in lowercase solved the issue.

H_end-rik
  • 551
  • 1
  • 6
  • 19
-1

I think the problem is in "const" that you use to declare the variable "User". Try to use "var" instead of .

//user.js
var User = mongoose.model('User', userSchema)
module.exports = User

//In other files
var User = require('../models/User')

P/S: This is link that clarify more about "const" and "var":

Const in javascript? When to use it and is it necessary

Hope it helpful for you !

Community
  • 1
  • 1
Tan Le
  • 187
  • 4