Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should methods be defined on Models in Mongoose or in a separate layer?

I'm a traditional C# developer and in the past I used MVC with tiered architectures. I'm now written an app with NodeJs/Mongoose and I'm a bit puzzled by how Mongoose works.

In the past I would define my models as simple POCO's, pass them through the layers and my repository would do all my data access.

With Mongoose it that the data access happens on the Model itself. You can call .save(), declare static and instance methods e.g. myModel.findAllByX(), etc. Although this is a departure for me I can see some pro's and con's to this.

Am I missing something here? Is there any good practice tips, or should I keep it simple and just declare everything on my Mongoose model as opposed to passing it to another layer?

like image 482
Click Ahead Avatar asked Jan 24 '13 12:01

Click Ahead


1 Answers

Since mongoose is already an abstraction on the database layer, you should do exactly what you suspect and build your model abstractions directly in mongoose.

That's what the static and method system is for on Mongoose models - that's also what the hook system is for (pre-init, save, etc).

In large applications, we typically end up accessing our mongoose models purely through custom statics and methods... in this sense, you could make the argument that those statics and methods actually compose the 'separate layer' you're talking about from MVC.

  • http://mongoosejs.com/docs/guide.html#statics
  • http://mongoosejs.com/docs/guide.html#methods
like image 78
hunterloftis Avatar answered Oct 24 '22 09:10

hunterloftis