Damien
Damien

Reputation: 4121

Mongoose - Multiple models for 1 schema

I am using mongoose v5.2.17. I was wondering is it possible to have multiple models map to the 1 schema. For example - I have the following model

const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    trim: true,
    minlength: 1,
    unique: true,
    validate: {
      validator: validator.isEmail,
      message: '{VALUE} is not a valid email',
    },
  },
  password: {
    type: String,
    required: true,
    minlength: 6,
  },  
  isTrialUser: {
    type: Boolean,
    default: true,
  },
  isAdminUser: {
    type: Boolean,
    default: false,
  }
});

UserSchema.methods.toJSON = function () {
  const user = this;
  const userObject = user.toObject();

  return _.pick(userObject, ['_id', 'email', 'isTrialUser']);
};


UserSchema.pre('save', function (next) {
  const user = this;

  if (user.isModified('password')) {
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(user.password, salt, (hashErr, hash) => {
        user.password = hash;
        next();
      });
    });
  } else {
    next();
  }
});

const User = mongoose.model('User', UserSchema);

module.exports = { User, UserSchema };

Is it possible for me to create another AdminModel where admin specific methods can live? I also want to return all data from the toJSON method from the AdminModel.

Please let me know if this is possible or if there is a better way to perform such a task

Thanks Damien

Upvotes: 0

Views: 1944

Answers (1)

Akrion
Akrion

Reputation: 18525

If I am understanding you correctly you want to inherit the UserModel in an AdminModel and decorate that one with extra methods etc. For that you can use util.inherits (or the so called Mongoose discriminators) like so:

function BaseSchema() {
  Schema.apply(this, arguments);

  this.add({
    name: String,
    createdAt: Date
  });
}
util.inherits(BaseSchema, Schema);

var UserSchema = new BaseSchema();
var AdminSchema = new BaseSchema({ department: String });

You can read more about it in Mongoose docs.

There is also a good article on the mongoose discriminators here

Upvotes: 2

Related Questions