I need to maintain a collection ‘users’ of [User] documents for implementing an authentication mechanism for my site.
[User] ~ {color: string, username:string, password-hash:string, password-salt: string}
Additionally, each [User] can be one of 3 colors – [RedUser], [BlueUser] and [GreenUser] and will have differing schemas depending on color. All extending from the [User] schema:
[RedUser] ~ Union( [User], {redfield:string} )
[GreenUser] ~ Union( [User], {greenfield:boolean} )
[BlueUser] ~ Union( [User], {bluefield:number} )
e.g. a green user – {color:’green’,username:’bob’,password-hash:’1313a…’,password-salt:’…’}
For authentication I want to query the ‘users’ collection using the general [User] schema, as all I need to know is the password-hash.
However, I would like a function as follows (pseudocode):
Authenticate( username, password )
userDoc <- users.findOne({username:username})
if badPassword(usersDoc.password-hash,password) throw error
else
if userDoc.color=='red'
return recast(userDoc, RedUser)
if userDoc.color=='green'
return recast(userDoc, BlueUser)
if userDoc.color=='blue'
return recast(userDoc, GreenUser)
So how could I do the up-casting from a [User] document to a [RedUser] for example?
I am using Node.js/MongooseJs/Coffeescript
thanks!
Pretty simple really, we just make use of the tiny but useful
mongoose-schema-extendpackage from https://github.com/briankircho/mongoose-schema-extend