微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 在另一个模型中为不同文件中的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);
}

解决方法

您可以从模型实例直接访问底层模式,如下所示:
module.exports = function (connection) {
    var mongoose = require('mongoose'),Role = require('./role.js'),RoleSchema = mongoose.model('Role').schema,role: [RoleSchema]
    });

    return mongoose.model('User',user);
}

原文地址:https://www.jb51.cc/nodejs/241043.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐