¿Se puede usar el almacenamiento en caché del módulo Node.js para crear singletons accesibles globalmente?

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 clase dentro del model.js module and then require this model.js module everywhere I need it?

Algo como esto:

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?

preguntado el 01 de julio de 12 a las 15:07

2 Respuestas

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

Respondido 01 Jul 12, 15:07

Thanks. I realised that I could get my mongoose models simply by writing User = mongoose.model('User') from any module, so they seem to be using that pattern. - Vaughan

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.

Respondido 04 Jul 12, 11:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.