Automattic/mongoose · error · Error

Can't set discriminator key "${key}"

Error message

Can't set discriminator key "${key}"

What it means

Error "Can't set discriminator key "${key}"" thrown in Automattic/mongoose.

Source

Thrown at lib/helpers/model/discriminator.js:190

    // Clean up conflicting paths _after_ merging re: gh-6076
    for (const conflictingPath of conflictingPaths) {
      delete schema.paths[conflictingPath];
    }

    // Rebuild schema models because schemas may have been merged re: #7884
    schema.childSchemas.forEach(obj => {
      obj.model.prototype.$__setSchema(obj.schema);
    });

    const obj = {};
    obj[key] = {
      default: value,
      select: true,
      set: function(newName) {
        if (newName === value || (Array.isArray(value) && utils.deepEqual(newName, value))) {
          return value;
        }
        throw new Error('Can\'t set discriminator key "' + key + '"');
      },
      $skipDiscriminatorCheck: true
    };
    obj[key][schema.options.typeKey] = existingPath ? existingPath.options[schema.options.typeKey] : String;
    schema.add(obj);

    schema.discriminatorMapping = { key: key, value: value, isRoot: false };

    if (baseSchema.options.collection) {
      schema.options.collection = baseSchema.options.collection;
    }
    const toJSON = schema.options.toJSON;
    const toObject = schema.options.toObject;
    const _id = schema.options._id;
    const id = schema.options.id;

    const keys = Object.keys(schema.options);
    schema.options.discriminatorKey = baseSchema.options.discriminatorKey;

View on GitHub (pinned to 49cdab0136)

When it happens

Trigger: Thrown at lib/helpers/model/discriminator.js:190 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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