Automattic/mongoose · error · MongooseError
Cannot overwrite Schema.indexTypes
Error message
Cannot overwrite Schema.indexTypes
What it means
Schema.indexTypes is a read-only static listing the valid index types ('2d', '2dsphere', 'hashed', 'text'); mongoose installs a getter with a throwing setter so this lookup table cannot be silently replaced. Any assignment to the property raises this error.
Source
Thrown at lib/schema.js:2531
};
const indexTypes = '2d 2dsphere hashed text'.split(' ');
/**
* The allowed index types
*
* @property {string[]} indexTypes
* @memberOf Schema
* @static
* @api public
*/
Object.defineProperty(Schema, 'indexTypes', {
get: function() {
return indexTypes;
},
set: function() {
throw new MongooseError('Cannot overwrite Schema.indexTypes');
}
});
/**
* Returns a list of indexes that this schema declares, via `schema.index()` or by `index: true` in a path's options.
* Indexes are expressed as an array `[spec, options]`.
*
* #### Example:
*
* const userSchema = new Schema({
* email: { type: String, required: true, unique: true },
* registeredAt: { type: Date, index: true }
* });
*
* // [ [ { email: 1 }, { unique: true } ],
* // [ { registeredAt: 1 }, {} ] ]
* userSchema.indexes();
*View on GitHub (pinned to 49cdab0136)
Solutions
- Delete the assignment - indexTypes is informational and not user-configurable.
- Create exotic indexes directly on the collection with the driver (collection.createIndex) instead.
- Audit Object.assign/extend calls targeting Schema and skip read-only statics (getter without setter).
Example fix
// before
mongoose.Schema.indexTypes = ['2d', '2dsphere', 'myIndexType'];
// after
schema.index({ loc: '2dsphere' }); // declare supported index types per-path
await model.collection.createIndex({ a: 1 }, { unique: true }); // exotic options go to the driver Defensive patterns
Strategy: validation
Validate before calling
const safeAssignStatics = (target, source) => {
for (const k of Object.keys(source)) {
const d = Object.getOwnPropertyDescriptor(target, k);
if (d && d.get && !d.set) continue; // skip read-only statics like indexTypes
target[k] = source[k];
}
}; Prevention
- Treat mongoose class statics as read-only; check docs before assigning.
- When stubbing in tests, use jest.spyOn on getters instead of assignment.
- Audit generic Object.assign/extend helpers that target library classes.
When it happens
Trigger: A direct write such as `mongoose.Schema.indexTypes = [...]`; helper code that copies statics via Object.assign(Schema, src); monkey-patching or test stubbing that treats class statics as writable.
Common situations: Attempting to extend the allowed index types (not supported - index types come from the server/driver); generic merge/extend utilities applied to the Schema class; migration scripts that clone mongoose internals.
AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21).
Data as JSON: /api/errors/165a3cb1904bacc0.
Report an issue: GitHub.