OOP with MVC using Mongoose & Express.js

I am creating an Express.js application where I want to use the MVC and Mongoose pattern to map documents in a MongoDB database. I created a folder for models and I want to get everything from abstract classes (Javascript) to better organize my code.

I am confused that the best way is to organize abstract classes and set the default values ​​that should be in every instance of the models. For example, one way is to use Mongoose schemas for abstract classes and then use Mongoose models for the models themselves:

Feline.js:

var mongoose = require('mongoose');

var Feline = mongoose.Schema({
  size: 'Number'
});

Feline.methods.getSize = function () {
  return this.size;
}

module.exports = Feline;

      

HouseCat.js:

var mongoose = require('mongoose')
, FelineSchema = require('./Feline.js');

var HouseCatModel = mongoose.model('HouseCat', FelineSchema)
, HouseCat = new HouseCatModel({
  size: 1 //Domesticated cats are small
});

module.exports = HouseCat;

      

There are several problems with this design. First, I think there must be a better way to set specific properties for each model without instantiating a new model object every time the client wants to create a new instance of the model type. For another, using this schema Mongoose is required in every model file and the code is customized specifically to use mongoose, which means it will be difficult to switch to a different ODM if we want to do so in the future.

Is there a better way to code this? And is there a design pattern that is easy enough to implement in Node that makes it easy to change the ODM?

+3


source to share


1 answer


Since the mongoose is specific to the mongodba, it will be a difficult task to distract her behavior.

The easiest way to do this is to set the interface for all ODMs and use the adapter pattern where mongoose is "adapted". Then you can use a module providing some dependency injection to replace the ODM in use.



Since this is a very long task, I cannot give you the code. Moreover, it can be a pain to implement this kind of thing in javascript because it doesn't provide strong OOP natively. However, I can suggest you take a look at some frameworks that can help you do this, like Danf , which provides a strong OOP paradigm with interfaces, classes, inheritance, and powerful dependency injection.

+1


source







All Articles