Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring model schemas in another model for mongoose in different files

I am trying to require my model in a model. I am sure that my path for requiring is correct as there is no error in my require, but it seems like it is not triggering my model whenever I save a new instance. What am I missing here?

role.js

module.exports = function () {
    var mongoose = require('mongoose'),
        Schema = mongoose.Schema;

    var role = new Schema({
        type: String,
        level: Number,
    });

    role.pre("save",function(next) {
        this.type = 'member';
        this.level = 0;

        next();
    });

    return mongoose.model('Role', role);
}

user.js

module.exports = function (connection) {
    var mongoose = require('mongoose');
        Role = require('./role.js'),
        Schema = mongoose.Schema;

    var user = new mongoose.Schema({
        first_name: String,
        last_name: String,
        email: String,
        password: String,
        profile_image: String,
        company_name: String,
        type: [{ type : String, default: 'Local' }],
        created_at: { type : Date, default: Date.now },
        created_by: { type: Schema.Types.ObjectId, ref: 'User' },
        role: [Role]
    });

    return connection.model('User', user);
}
like image 738
Gene Lim Avatar asked Nov 26 '15 08:11

Gene Lim


1 Answers

You can get direct access of the underlying schema from a model instance as follows:

module.exports = function (connection) {
    var mongoose = require('mongoose'),
        Role = require('./role.js'),
        RoleSchema = mongoose.model('Role').schema,
        Schema = mongoose.Schema;

    var user = new mongoose.Schema({
        first_name: String,
        last_name: String,
        email: String,
        password: String,
        profile_image: String,
        company_name: String,
        type: [{ type : String, default: 'Local' }],
        created_at: { type : Date, default: Date.now },
        created_by: { type: Schema.Types.ObjectId, ref: 'User' },
        role: [RoleSchema]
    });

    return mongoose.model('User', user);
}
like image 79
chridam Avatar answered Sep 20 '22 00:09

chridam