Simon
Simon

Reputation: 147

Mongoose.js ignoring default value in subdoc Schema

I am currently writing a web app with mongodb and mongoose. I defined a document schema, that has has an array of subdocuments. I defined the subdocs in a different Schema. The subdocuments have fields with default values, for example: end: {type: Date, default: Date.now}. Unfortunately on creating the parent doc with some subdocs only the fields of the subdoc are set which I set explicitly. It seems that mongoose is ignoring the default option.

Do you guys have any ideas what I am doing wrong?

Edit:

employment.model.js

var Shift = require('./shift.model.js').ShiftSchema;

var EmploymentSchema = new Schema({
    title: {type: String, required: true},
    ....
    shifts: [Shift]
});

shift.model.js

var ShiftSchema = new Schema({
   title: {type: String},
   ....
   info: {type:String, default: 'Hallo'},
   start: {type: Date, default: Date.now, index: true},
   end: {type: Date, default: Date.now}
});
module.exports.ShiftSchema = ShiftSchema;
module.exports = mongoose.model('Shift', ShiftSchema);

None of the above default values are set. My mongoose.js version is: ~3.8.8

Sample Shift Creation

Employment.create({
    title: 'PopulateDB Employ',
    start: new Date(),
    customer: result.customer,
    shifts: [{
      title: 'Shift 1',
      start: new Date()
    },{
      title: 'Shift 2',
      start: new Date()
    }]
  },cb)

Upvotes: 1

Views: 859

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

You're overwriting your export of ShiftSchema with the next statement that assigns the model as the only export of the module. The result is that Shift is ending up as undefined in employment.model.js.

Change the first line of that file to the following to access the schema from the exported model:

var Shift = require('./shift.model.js').schema;

and just remove the module.exports.ShiftSchema = ShiftSchema; line in shift.model.js.

Upvotes: 1

Related Questions