node.jsexpressmongoosemongoose-schemadiscriminator

How to get a list of available Mongoose Discriminators?


Given a situation where you have a User Scheme that you use to create a base model called User. And then for user roles, you use mongoose discriminators to create inherited models called Admin, Employee and Client. Is there a way to programmatically determine how many discriminations/inheritances/roles of the User model are available, as well as the available names?

My question in terms of code:

File: models/user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var options = {discriminatorKey: 'role'};

var userSchema = mongoose.Schema({
  name: String,
  email: String,
  password: String,
},options);

var User = mongoose.model('User', userSchema);

var Client = User.discriminator("Client", mongoose.Schema({
  Address : String,
  Tax_identification : String,
  Phone_number : String,
  Internal_Remarks : String,
  CRM_status : String,
  Recent_contact : String,
}));
var Employee = User.discriminator("Employee",mongoose.Schema({
  Staff_Id: String,
}));

module.exports = {User: User, Client: Client, Employee: Employee };

File: controllers/usersController.js

var User = require('../models/user.js').User;


module.exports = {
  registerRoutes: function(app){
     app.get('user/create',this.userCreateCallback)
  },

  userCreateCallback: function(req,res){

    //Get Available User Roles - The function below doesn't exist, 
    //Just what I hypothetically want to achieve:

    User.geAvailableDiscriminators(function(err,roles){

      res.render('user/create',{roles:roles})      

    });

  }
};

I hope I managed to express what I want to do. Alternative approaches are also welcome.


Solution

  • Since v4.11.13, mongoose model has model.discriminators which is an array of models, keyed on the name of the discriminator model.

    In your case if you do console.log(User.discriminators) you will get:

    {
      Client: {
        ....
      },
      Employee: {
      }
    }
    

    As far as I can see, this is not documented anywhere.

    Line 158 in lib.helpers.model.discriminators.js is where this is created.