Automattic/mongoose · error · TypeError
A getter must be a function.
Error message
A getter must be a function.
What it means
SchemaType#get registers a getter function on a path and throws a TypeError for any non-function argument (lib/schemaType.js:899). Like the setter variant, it guards against strings, undefined variables, and other non-callables before pushing to the getters array.
Source
Thrown at lib/schemaType.js:899
* name: { type: String, required: true, get: inspector },
* taxonomy: { type: String, get: inspector }
* })
*
* const Virus = db.model('Virus', VirusSchema);
*
* Virus.findById(id, function (err, virus) {
* console.log(virus.name); // name is required
* console.log(virus.taxonomy); // taxonomy is not
* })
*
* @param {Function} fn
* @return {SchemaType} this
* @api public
*/
SchemaType.prototype.get = function(fn) {
if (typeof fn !== 'function') {
throw new TypeError('A getter must be a function.');
}
this.getters.push(fn);
return this;
};
/**
* Adds multiple validators for this document path.
* Calls `validate()` for every element in validators.
*
* @param {(RegExp|Function|object)[]} validators
* @returns {SchemaType}
*/
SchemaType.prototype.validateAll = function(validators) {
for (let i = 0; i < validators.length; i++) {
this.validate(validators[i]);
}
return this;View on GitHub (pinned to 49cdab0136)
Solutions
- Pass a function reference: `schema.path('name').get(v => v?.toUpperCase())`
- Guard optional getters: `if (typeof fn === 'function') path.get(fn)`
- Fix the import/variable name that resolved to undefined
Example fix
// before
schema.path('dob').get('toISOString'); // throws TypeError
// after
schema.path('dob').get(v => (v ? v.toISOString() : v)); Defensive patterns
Strategy: type-guard
Validate before calling
function addGetter(schematype, fn) {
if (typeof fn !== 'function') {
throw new TypeError(`getter for ${schematype.path} must be a function, got ${typeof fn}`);
}
return schematype.get(fn);
} Type guard
const isFunction = v => typeof v === 'function';
Prevention
- Pass function references or arrow functions, never method-name strings
- Guard optional config getters before registering them
- Prefer module-level named functions so stack traces stay readable
When it happens
Trigger: `schema.path('name').get('toJSON')`; `.get(mask)` where mask is undefined due to a missed import; passing a config object instead of a function.
Common situations: Config-driven getter wiring; optional features where the getter key is absent (`config.formatter` undefined); copy-paste of getter names as strings from documentation.
Related errors
- A setter must be a function.
- Arguments must be aggregate pipeline operators
- Union schema type requires an array of types
- Invalid addFields() argument. Must be an object
- Invalid project() argument. Must be string or object
AI-assisted analysis of Automattic/mongoose@49cdab0136 (2026-08-21).
Data as JSON: /api/errors/3c009fc19981338c.
Report an issue: GitHub.