Reputation: 305
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 .
Upvotes: 1
Views: 604
Reputation: 1238
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.
Upvotes: 1