在另一个模型中需要模型模式用于不同文件中的猫鼬

时间:2015-11-26 08:48:59

标签: node.js mongodb model mongoose

我试图在模型中要求我的模型。我确信我的要求路径是正确的,因为我的要求没有错误,但似乎每当我保存新实例时它都不会触发我的模型。我在这里缺少什么?

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);
}

1 个答案:

答案 0 :(得分:8)

您可以从模型实例直接访问底层架构,如下所示:

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);
}