vaughan
vaughan

Reputation: 7445

Can Node.js module caching be used to create globally accessible singletons?

After splitting my project up into many OO classes I am having to pass a reference to my Model instance (contains Mongoose models and schema) through multiple constructors.

Would it be bad practice to create an instance of the Model class inside the model.js module and then require this model.js module everywhere I need it?

Something like this:

Model = function () { ... }

module.exports = new Model();

This would rely on Node's module caching to allow the same Model instance to be shared between files, like having a global singleton.

Or should I explicitly pass dependencies through constructors?

Upvotes: 0

Views: 304

Answers (2)

Timothy Strimple
Timothy Strimple

Reputation: 23070

I would say yes, this is a bad practice and easily abused. It ensures tightly coupled modules and means that you're going to have to modify every file that touches the database if you ever move away from mongoose. It is bad for all of the same reasons why misusing singletons is bad.

Just because many people do something a particular way in no way indicates that it is a good thing to do.

Upvotes: 1

Pavan Kumar Sunkara
Pavan Kumar Sunkara

Reputation: 3025

No, it's not a bad practice. In fact, many people do it this way.

Upvotes: 1

Related Questions