Mongoose discriminators, instantiate documents Mongoose discriminators, instantiate documents mongoose mongoose

Mongoose discriminators, instantiate documents


A better implementation should be to use an object instead of a switch.

var modelMap = {  'GenericEvent': GenericEventModel,  'ClickedLinkEvent': ClickedLinkEventModel,  'SignedUpEvent': SignedUpEventModel};function getMongooseModel(type) {  return modelList[type];}

After that in order to avoid errors you can use Mongoose#plugin(fn, [opts]) in order to populate the modelMap object.

Or you can just use Mongoose#model(name, [schema], [collection], [skipInit]).

Defines a model or retrieves it.

Something like this should work:

module.exports.createEvent = function(req, res, next) {  var Model = mongoose.model(req.params.type);  (new Model(req.body)).save(next);}

With a proper declaration of your model class in mongoose, model name must match your request parameter of course.

var GenericEventModel = mongoose.model('GenericEvent', GenericEventModelSchema);