javascript - Node.JS with Mongoose OOP - how to separate mongoose data access code from pure data object? -
i came across bit of design problem mongoose - maybe following wrong approach?
in old oop style want have class called user. class has several member such username, firstname, lastname, salt , hash, , has method called authenticate takes hashed password argument. fill user object data, need write code this, far aware:
var userschema = mongoose.schema({ firstname: string, lastname: string, username: string, salt: string, hashed_pwd:string }); userschema.methods = { authenticate: function(passwordtomatch) { return crypto.hashpwd(this.salt, passwordtomatch) === this.hashed_pwd; } }
this code cluttered mongoose specific code - calling mongoose.schema, , add method have use userschema.methods. when tried declare user class separately , tried create mongoose schema out of it, encountered kinds of errors, , member method not recognised.
so when want use different database using same schema, have redeclare everything. want declare schemas separately reoccure on place in application.
is there elegant solution this, there different library can use, or following wrong approach?
thanks in advance..
this perhaps partial answer, might guide in useful direction.
it's worth understanding mongoose , does. mongoose odm (not orm—read here difference. tl;dr: odm nosql orm sql; non-relational db relational db.) mongoose helps abstract of boilerplate boring stuff validations; stuff want when dealing data in or being written database. basis of validation comes mongoose.schema
define each model should contain , each property on model should cast (i.e. username should string, updatedon should datestamp.)
if want code database-agnostic (that is, not requiring specific database), mongoose not you're looking for. if not being tied specific db important you, should try looking database agnostic orm/odm. @ moment, waterline comes mind.
it should mentioned that, if don't care validations, data casting, etc. mongoose provides, roll vanilla mongodb queries , stick whatever json-compatible javascript object (nosql) database. not recommended unless understand lose / risk in doing so.
i might argue that, authenticate method has no place being in model , should instead exist in position previous model/database interaction (e.g. in controller or equivalent if you're not following mvc conventions.)
Comments
Post a Comment