真的很简单,我们只使用来自https://github.com/briankircho/mongoose-schema-extendmongoose-schema-extend
的小而有用的包
###
Dependencies.
###
mongoose = require('mongoose')
extend = require('mongoose-schema-extend')
###
Main
###
class Demo
constructor: (dbUrl)->
@db = mongoose.createConnection( dbUrl )
userSchema = new mongoose.Schema
username : { type: String, default: "" }
password_hash : { type: String, default: "" }
,
{collection : 'users', discriminatorKey : 'color'}
userSchema.methods.verifyPassword = (pass)->
console.log("is it a good password? " + (this.password_hash==pass))
redSchema = userSchema.extend
redfield : { type: String, default: "red" }
redSchema.methods.printColor = ->
console.log("RED!")
blueSchema = userSchema.extend
bluefield : { type: String, default: "blue" }
blueSchema.methods.printColor = ->
console.log("BLUE!")
greenSchema = userSchema.extend
greenfield : { type: String, default: "green" }
greenSchema.methods.printColor = ->
console.log("GREEN!")
# create the mongoose db models
@UserModel = @db.model('User', userSchema)
@RedModel = @db.model('Red', redSchema)
@BlueModel = @db.model('Blue', blueSchema)
@GreenModel = @db.model('Green', greenSchema)
populate: ->
user1 = new @RedModel({username:'user1',password_hash:'pass1',redfield:'blabla'})
user1.save()
user2 = new @GreenModel({username:'user2',password_hash:'pass2',greenfield:'blabla2'})
user2.save()
user3 = new @RedModel({username:'user3',password_hash:'pass3',redfield:'blabla3'})
user3.save()
user4 = new @GreenModel({username:'user4',password_hash:'pass1',greenfield:'dflabla'})
user4.save()
user5 = new @BlueModel({username:'user5',password_hash:'pass2',bluefield:'blabla2'})
user5.save()
user6 = new @BlueModel({username:'user6',password_hash:'pass3',bluefield:'blabla3'})
user6.save()
auth:(username,callback)->
@UserModel.findOne({ username: username }, callback)
###
Start the demo
###
demo = new Demo('mongodb://localhost/testpolymorph')
demo.populate()
demo.auth 'user5', (err,userDoc)->
userDoc.verifyPassword("pass")
userDoc.printColor()
demo.auth 'user3', (err,userDoc)->
userDoc.verifyPassword("pass3")
userDoc.printColor()
demo.auth 'user4', (err,userDoc)->
userDoc.verifyPassword("pass3")
userDoc.printColor()