У меня есть 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
, как показано на рисунке выше. Однако, когда я пытаюсь ссылаться на shiftSchema
в daySchema
, я получаю сообщение об ошибке:
TypeError: Invalid value for schema Array path
shifts``. Однако, когда я попытался скопировать shiftSchema
в тот же файл, он сработал. Можно ли ссылаться на дочернюю схему (со всеми ее проверками), не имея ее в том же файле, что и родительская схема, или они должны быть в одном файле?
Вы правы экспорт 'shift' схемы! Я только экспортировал модель. Но изменение 'shifts: [shiftSchema]' to 'shifts: [Schema.Types.ObjectId]' приводит к ошибке. Можете ли вы отредактировать ответ, чтобы включить только изменение 'module.exports = shiftSchema', чтобы я мог принять ответ? Благодаря! – SalmaFG