pablopunk
pablopunk

Reputation: 371

Shoud I require a mongoose model or get it from mongoose directly

I have a model in a file models/Model.js like this:

const mongoose = require('mongoose')
const modelSchema = mongoose.Schema({ name: String })
const Model = mongoose.model('Model', modelSchema)
module.exports = Model

Then when I use it I import it like any other module:

const Model = require('../models/Model')

My question is: If every time I require a module the code is executed (in this case it would "run" Model.js every time I import it), would it be more efficient (or at least make more sense) to import it like this?:

const mongoose = require('mongoose')
const Model = mongoose.model('Model')

Upvotes: 1

Views: 223

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

Your question contains an incorrect assumption:

If every time I require a module the code is executed (in this case it would "run" Model.js every time I import it)...

The code in Model.js is only run the first time require is called to load that module. The resulting module object is then placed in require.cache and subsequent require calls for that same module simply return the same module object from the cache.

So there's no meaningful performance difference between the two approaches and it's up to your personal preference.

Upvotes: 2

Related Questions