1

I'm using nodejs and have a register page that has a select tag to choose between Client and Employee.

I want to have 1 Model and 2 Schemas: -User: will contains commun props eg:mail,name,pass... -EmployeeSchemma with specific fileds for an employee -ClientSchemma with specific fields for a client.

this is what In want to achieve in my server side :

var User=require("models/user");

router.post("/register",function(req,res){
var newUser=new User();

if(req.body.type=="client")
   //  make the newUser use the ClientSchema //

if(req.body.type=="employee")
  //   the newUser instance will use the EmployeeSchema //
});

Please how can I achieve such a result (?) note that I just want to use one single Model that can modelise both Client and Employee users depending on the user choice in the form .

user3711521
  • 285
  • 5
  • 14
  • this might be useful: http://stackoverflow.com/questions/14453864/use-more-than-one-schema-per-collection-on-mongodb – devonj Jul 28 '16 at 23:13
  • thank you for the answer, but this not what I'm looking for, what I want is to use one data structure object : something like that : var generic=require('/models/dynamicModel'); and then this object can set client fields if it's a client or employee fields if it's an employee – user3711521 Jul 29 '16 at 03:48

1 Answers1

1

If you want a "dynamic model" I think you are looking for the setting strict to false in mongoose

As you know by default, Mongoose will follow the schema/model you have set-up, setting strict: false will allow you to save fields that are not in your schema/model.

So for your case, in your file models/user, you'll want to include "strict: false" as your second argument when creating your schema:

var userSchema = new Schema({
    email: String,
    name: String,
    password: String
    // other parts of your user schema
}, {strict: false})

You should be able to set the client and employee fields accordingly in the same collection now.

devonj
  • 1,198
  • 1
  • 13
  • 24