Skip to content

Mongoose 8.7.2 breaks Union Types #15057

@timheerwagen

Description

@timheerwagen

Prerequisites

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

Mongoose version

8.7.2

Node.js version

22

MongoDB server version

6.11

Typescript version (if applicable)

5.7.2

Description

Before 8.7.2, only the type of the union was returned and that was fine. But now the type is returned as binary, but the union has no binaries in it.
It does not matter that the correct union value is not parsed here by mongoose, as this is done by zod.
This error seems to be related to this issue: #14974

Steps to Reproduce

import mongoose, { Model } from "mongoose";

type Attachment =
  | {
      type: "foo";
      value?: undefined;
    }
  | {
      type: "string";
      value?: string;
    };

const TestSchema = new mongoose.Schema<Attachment>({
  type: { type: String, required: true },
  value: { type: String },
});

export const AttachmentModel = mongoose.model<Attachment>("test", TestSchema);

const main = async () => {
  const item = await AttachmentModel.findOne().lean();

  if (!item) return;

  doSomeThing(item);
};

const doSomeThing = (item: Attachment) => {
  console.log(item);
};

doSomeThing returns error
Image

Expected Behavior

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    has repro scriptThere is a repro script, the Mongoose devs need to confirm that it reproduces the issuetypescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions