Node.JS with Mongoose OOP - how to separate mongoose data access code from pure data object? Node.JS with Mongoose OOP - how to separate mongoose data access code from pure data object? mongoose mongoose

Node.JS with Mongoose OOP - how to separate mongoose data access code from pure data object?


This is perhaps a partial answer, but it might help guide you in a useful direction.

It's worth understanding what mongoose is and what it does. Mongoose is an ODM (not an ORM—read here for the difference. TL;DR: ODM is to NoSQL as ORM is to SQL; non-relational DB to relational DB.) Mongoose helps abstract some of the boilerplate boring stuff like validations; stuff you want when dealing with a data in or being written into a database. The basis of this validation comes from mongoose.Schema with which you define what each model should contain and what each property on a model should be cast as (i.e. username should be a string, updatedOn should be a datestamp.)

If you want your code to be database-agnostic (that is, not requiring any specific database), Mongoose is not what you're looking for. If not being tied to any specific DB is important to you, you should try looking for a database agnostic ORM/ODM. At the moment, Waterline comes to mind.

It should be mentioned that, if you don't care about validations, data casting, etc. that mongoose provides, you could just roll vanilla MongoDB queries and stick whatever JSON-compatible JavaScript object into your (NoSQL) database. But this is not recommended unless you fully understand what you lose / risk in doing so.

I might also argue that, the authenticate method has no place being in your model and should instead exist in a position previous to any model/database interaction (e.g. in a controller or the equivalent if you're not following MVC conventions.)