Polymorphic user model with mongoose and node.js
Asked Answered
B

1

5

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?

Bonar answered 3/7, 2014 at 18:45 Comment(1)
Did you get anywhere with this? Looking to do polymorphic relations too, and I'm also from a Rails background.Trahurn
B
8

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

Bonar answered 4/3, 2016 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.