Skip to content

TypeScript this Context Error When Calling Static Method on Schema Using timestamps and SchemaOptions.virtuals #16046

Description

@xGeekoo

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

9.2.2

Node.js version

24.13.1

MongoDB server version

8.2

Typescript version (if applicable)

5.9.3

Description

A TypeScript error occurs when calling a static method on a Mongoose model whose schema includes:

  • timestamps: true
  • a virtual populate defined via SchemaOptions.virtuals
  • statics defined inside SchemaOptions.statics

The following TypeScript error occurs when calling a static method.
The error originates from an incompatibility in the inferred this context of the static method.

The 'this' context of type
'Model<
  { placeholder?: unknown } & DefaultTimestampProps,
  {},
  {},
  { votes: unknown } & { id: string },
  Document<
    unknown,
    {},
    { placeholder?: unknown } & DefaultTimestampProps,
    { votes: unknown } & { id: string }
  >
>'
is not assignable to method's 'this' of type
'Model<
  { placeholder?: string | null | undefined },
  {},
  {},
  { votes: unknown },
  Document<
    unknown,
    {},
    { placeholder?: string | null | undefined },
    { votes: unknown } & { id: string },
    DefaultSchemaOptions
  >
>'.

The types of 'castObject(...).placeholder' are incompatible between these types.

Type 'unknown' is not assignable to type 'string | null | undefined'.

Steps to Reproduce

import mongoose from 'mongoose';

const issueOneSchema = new mongoose.Schema(
  { placeholder: String },
  {
    timestamps: true,
    virtuals: {
      votes: {
        options: {
          ref: 'IssueTwo',
          localField: '_id',
          foreignField: 'issueOneId'
        }
      }
    },
    statics: {
      myStaticMethod: function () {
        console.log('placeholder');
      }
    }
  }
);

const IssueOne = mongoose.model('IssueOne', issueOneSchema);

IssueOne.myStaticMethod();

Metadata

Metadata

Assignees

No one assigned

    Labels

    can't reproduceMongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.typescriptTypes or Types-test related issue / Pull Request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions