Automattic/mongoose · error · MongooseError

Cannot set default value of path `${this.path}` to a mongoos

Error message

Cannot set default value of path `${this.path}` to a mongoose Schema instance.

What it means

SchemaType#default rejects mongoose Schema instances as default values (lib/schemaType.js:478): a Schema defines structure, not a value, so it is almost always a key mix-up where the schema was meant to be the field's type (a subdocument), not its default.

Source

Thrown at lib/schemaType.js:478

 *     m1.mixed.added = 1;
 *     console.log(m1.mixed); // { added: 1 }
 *     const m2 = new M;
 *     console.log(m2.mixed); // { added: 1 }
 *
 * @param {Function|any} val The default value to set
 * @return {any|undefined} Returns the set default value.
 * @api public
 */

SchemaType.prototype.default = function(val) {
  if (arguments.length === 1) {
    if (val === void 0) {
      this.defaultValue = void 0;
      return void 0;
    }

    if (val?.instanceOfSchema) {
      throw new MongooseError('Cannot set default value of path `' + this.path +
        '` to a mongoose Schema instance.');
    }

    this.defaultValue = val;
    return this.defaultValue;
  } else if (arguments.length > 1) {
    this.defaultValue = [...arguments];
  }
  return this.defaultValue;
};

/**
 * Declares the index options for this schematype.
 *
 * #### Example:
 *
 *     const s = new Schema({ name: { type: String, index: true })
 *     const s = new Schema({ name: { type: String, index: -1 })

View on GitHub (pinned to 49cdab0136)

Solutions

  1. Define the path as a subdocument instead: `new Schema({ child: childSchema })` or `{ child: { type: childSchema } }`
  2. If you want a default empty object, use a function: `default: () => ({})` (returning a fresh object per document)

Example fix

// before
new Schema({ child: { type: String, default: childSchema } }); // throws

// after
new Schema({ child: { type: childSchema, default: () => ({}) } });
Defensive patterns

Strategy: validation

Validate before calling

function assertValidDefault(path, def) {
  if (def?.instanceOfSchema) {
    throw new TypeError(`default for ${path} must be a value or a function, not a Schema; put the schema in 'type' instead`);
  }
}

Type guard

const isSchemaInstance = v => Boolean(v?.instanceOfSchema);

Prevention

When it happens

Trigger: `new Schema({ child: { type: String, default: childSchema } })`; `schema.path('child').default(childSchema)`; converting an object-literal field to a subdocument and leaving the schema in the wrong slot.

Common situations: Refactoring inline objects into named schemas; copy-paste from subdocument examples; tutorial code that mixes `type` and `default` keys.

Related errors


AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21). Data as JSON: /api/errors/469e3369cffeff34. Report an issue: GitHub.