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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With