Skip to content

Conversation

@sderrow
Copy link
Contributor

@sderrow sderrow commented Sep 13, 2025

Summary

Currently, the SchemaType property of schema is required in the type definition and its JSDoc describes the property as "The schema this SchemaType instance is part of".

Instead, based on how mongoose actually works, it should be optional and the JSDoc should be changed, since it's not actually the Schema that the SchemaType is part of. Instead, the schema property only exists when the SchemaType is for a subdocument or document array and it refers to the actual subdocument schema itself.

Examples

Here's an example showing how the schema property isn't present on every SchemaType, just to prove that the Typescript definition should be changed to optional and its JSDoc should be modified accordingly.

import mongoose from "mongoose";

type Person = {
  _id: mongoose.Types.ObjectId;
  name: string;
  doc: {
    _id: mongoose.Types.ObjectId;
    title: string;
  };
};

const personSchema = new mongoose.Schema<Person>(
  {
    name: { type: String, required: true },
    doc: {
      type: {
        title: String,
      },
    },
  },
  { versionKey: false },
);

const Person = mongoose.model("Person", personSchema);

for (const [path, schemaType] of Object.entries(personSchema.paths)) {
  let desc = "";
  if ("schema" in schemaType) {
    desc = Object.keys(schemaType.schema.paths).join(", ");
  } else {
    desc = "n/a";
  }
  console.log(`${path} --> ${desc}`);
  /* OUTPUT:
  name --> n/a
  doc --> title, _id
  _id --> n/a
  */
}

Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks 👍

@vkarpov15 vkarpov15 added this to the 8.18.2 milestone Sep 18, 2025
@vkarpov15 vkarpov15 merged commit 8a2b2cf into Automattic:master Sep 18, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants