将模型架构导入为子文档

Importing a model schema as a subdocument

我有 2 个独立的模型:

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 中,如上所示。但是,当我尝试在 daySchema 中引用 shiftSchema 时,出现错误:

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

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

我们怎么能说您正在将文档导出为文档而不是子文档?

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

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

所以,在我看来,您可以像这样重构您的 daySchema:

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

shifts 将包含班次文档的 objectId 数组。我个人觉得这种方法更好,但如果你想让你的代码 运行 那么就这样做:

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

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'
        }
    });
module.exports = shiftSchema