我想在模型中要求我的模型.我确信我的要求路径是正确的,因为我的要求没有错误,但似乎每当我保存新实例时它都不会触发我的模型.我在这里错过了什么?
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); }
解决方法
您可以从模型实例直接访问底层模式,如下所示:
module.exports = function (connection) { var mongoose = require('mongoose'),Role = require('./role.js'),RoleSchema = mongoose.model('Role').schema,role: [RoleSchema] }); return mongoose.model('User',user); }