Polymorphic user model with mongoose and node.js
mongodb, mongoose, node.js, polymorphic-associations
Solution
The scenairo can be handled with mognoose discriminators.
according to mongoose docs :
Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.
Theres not a lot of tutorials that I could find on discriminators but, heres a link that I found useful: http://thecodebarbarian.com/2015/07/24/guide-to-mongoose-discriminators
Thanks
Problem
I am making an application with the mean.js boilerplate. It is a recruitment engine with users as employers and candidates. Now Employers and candidates should be stored as separate documents and every user must have only one employer or a candidate, as every candidate or employer needs to login with the user object. I did this in rails with postgresql as: ``` ## User belongs_to :profileable, :polymorphic => true ## Candidate and Employer has_one :user, :as => :profileable ``` With mongoose this is what I've done so far using the package 'mongoose-schema-extend': ``` var extend = require('mongoose-schema-extend'); var UserSchema = new Schema({ email: { type: String }, password: { type: String } }, { collection: 'users', discriminatorKey : '_type' }); var CandidateSchema = UserSchema.extend({ Experience: { type: Number } }); var EmployerSchema = user.user.extend({ companyName: { type: String } }); ``` above code works but in mongodb only creates documents for users with _type attribute set as candidate or employer. What I think it should do is store candidates, employers and users as separate documents. I have to later associate employers to a company and jobs. Also I need to query candidates and employers separately with different criteria. What is the best approach to achieve the functionality?