SchemaType.prototype.default()

Parameters
  • val «Function|any» the default value
Returns:
  • «defaultValue»

Sets a default value for this SchemaType.

Example:

  1. const schema = new Schema({ n: { type: Number, default: 10 })
  2. const M = db.model('M', schema)
  3. const m = new M;
  4. console.log(m.n) // 10

Defaults can be either functions which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.

Example:

  1. // values are cast:
  2. const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
  3. const M = db.model('M', schema)
  4. const m = new M;
  5. console.log(m.aNumber) // 4.815162342
  6. // default unique objects for Mixed types:
  7. const schema = new Schema({ mixed: Schema.Types.Mixed });
  8. schema.path('mixed').default(function () {
  9. return {};
  10. });
  11. // if we don't use a function to return object literals for Mixed defaults,
  12. // each document will receive a reference to the same object literal creating
  13. // a "shared" object instance:
  14. const schema = new Schema({ mixed: Schema.Types.Mixed });
  15. schema.path('mixed').default({});
  16. const M = db.model('M', schema);
  17. const m1 = new M;
  18. m1.mixed.added = 1;
  19. console.log(m1.mixed); // { added: 1 }
  20. const m2 = new M;
  21. console.log(m2.mixed); // { added: 1 }