2016-12-28 64 views
0

我有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複製到相同的文件,它的工作。是否可以引用子模式(及其所有驗證),而不必將其與父模式放在同一文件中,還是必須位於同一文件中?

回答

1

基本上你正在合併子文檔和文檔的概念。在上面給出的模型中,您將創建兩個文檔,然後將一個文檔插入另一個文檔。

我們怎麼能說你將文件導出到文件而不是子文件?

答:出口這行代碼mongoose.model('Shift', shiftSchema) 使其完整的文檔

如果只導出module.exports = shiftSchema那麼你可以達到你[R想做什麼。

所以,在我看來,你可以調整你的daySchema這樣的:

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

轉變將包含的ObjectID的陣列轉移文件。我個人覺得這個方法比較好,但如果u想你的代碼運行,然後去這樣的:

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 
+0

你說得對有關導出'shift'模式!我只是出口模型。但是改變shift:[shiftSchema]到'shift:[Schema.Types.ObjectId]'會導致錯誤。你可以編輯答案,只包含'module.exports = shiftSchema'變化,所以我可以接受答案?謝謝! – SalmaFG