将模型架构导入为子文档

时间:2016-12-28 13:15:28

标签: mongoose mongoose-schema

我有两个独立的模型:

models/day.js:

var mongoose = require ('mongoose');
var Schema = mongoose.Schema;
var shiftSchema = require('./shift').shiftSchema;

var daySchema = new Schema({
    date: {
        type: String,
        required: true
    },
    shifts: [shiftSchema]
});
module.exports = {
     model: mongoose.model('Day', daySchema)
};

models/shift.js:

var mongoose = require ('mongoose');
var Schema = mongoose.Schema;

var shift_status_enum = {
  values: ['open', 'closed'],
  message: '`{VALUE}` is not a valid shift status.'
};
var shiftSchema = new Schema({
    start: {
        type: Number,
        required: true
    },
    end: {
        type: Number,
        required: true
    },
    status: {
        type: String,
        enum: shift_status_enum,
        required: true,
        default: 'open'
    }
});
shiftSchema.pre('save', function(next) {
    if (this.start >= this.end)
        return next(Error('error: Shift end must be greater than shift start.'));
    if(this.interval > this.end - this.start)
        return next(Error('error: Shift interval cannot be longer than the shift.'));
    else
        next();
});
module.exports = {
     model: mongoose.model('Shift', shiftSchema)
};

我试图将shifts数组嵌入到day中,如上所示。但是,当我尝试引用shiftSchema中的daySchema时,我收到错误:

TypeError: Invalid value for schema Array path shifts``。 但是,当我尝试将shiftSchema复制到同一个文件中时,它有效。是否可以引用子模式(及其所有验证)而不将其与父模式放在同一文件中,或者它们是否必须位于同一文件中?

1 个答案:

答案 0 :(得分:1)

基本上,您正在合并子文档和文档的概念。在上面给出的模型中,您将创建两个文档,然后将一个文档插入另一个文档。

我们怎么说您将文档导出到文档而不是子文档?

Ans:导出这行代码mongoose.model('Shift', shiftSchema) 使其完整的文件

如果您只导出module.exports = shiftSchema,那么您可以实现您想要做的事情。

所以,在我看来,你可以重新构建你的daySchema,如:

var daySchema = new Schema({
    date: {
        type: String,
        required: true
    },
    shifts: [Schema.Types.ObjectId]
});

shift将包含shift文档的objectIds数组。我个人认为这种方法更好,但如果你想让你的代码运行,那就去吧:

var mongoose = require ('mongoose');
var Schema = mongoose.Schema;
var shiftSchema = require('./shift');

var daySchema = new Schema({
    date: {
        type: String,
        required: true
    },
    shifts: [shiftSchema]
});
module.exports = {
     model: mongoose.model('Day', daySchema)
};

模型/ shift.js:

    var mongoose = require ('mongoose');
    var Schema = mongoose.Schema;

    var shift_status_enum = {
      values: ['open', 'closed'],
      message: '`{VALUE}` is not a valid shift status.'
    };
    var shiftSchema = new Schema({
        start: {
            type: Number,
            required: true
        },
        end: {
            type: Number,
            required: true
        },
        status: {
            type: String,
            enum: shift_status_enum,
            required: true,
            default: 'open'
        }
    });
module.exports = shiftSchema