How to get a list of available Mongoose Discriminators?
Asked Answered
A

2

8

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.

Aspic answered 31/12, 2017 at 18:35 Comment(0)
S
7

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.

Subvention answered 9/7, 2018 at 12:28 Comment(1)
i think it is mentioned in the mongoose API docs, but not at a usual place :). mongoosejs.com/docs/api.html#model_Model-discriminatorsSiblee
M
0

I think you want to fetch the names and values of all the discriminators as for the names you can simply use

User.discriminators

but for finding values you can use this

return Promise.all(Object.keys(discriminators).map(i => 
    discriminators[i].find({ userId: this._id }))
).then(promiseResults =>
    promiseResults.reduce((arr, el) => arr.concat(el), [])
);

you need to put userId under each discriminators for that.

Melodist answered 11/7, 2018 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.