Skip to content

Validation Bypass when Union of Objects is used in Schema #15732

@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.19.3

Node.js version

24.11.0

MongoDB server version

"mongodb-memory-server": "^10.3.0"

Typescript version (if applicable)

No response

Description

If a union of objects is used inside a schema and an arbitrary object is used upon creation, the first Object Schema is used but validation is skipped, at least for the required fields.

Defined field types still validate correctly, and it is not possible to save arbitrary fields.

The same thing happens when you use this with arrays of objects.

Steps to Reproduce

import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
import { inspect } from "node:util";

const SubSchema1 = new mongoose.Schema({
  price: { type: Number, required: true },
  title: { type: String },
  isThisSchema1: { type: Boolean },
});

const SubSchema2 = new mongoose.Schema({
  description: { type: String, required: true },
  title: { type: String },
  isThisSchema2: { type: Boolean },
});

const TestSchema = new mongoose.Schema({
  product: {
    type: mongoose.Schema.Types.Union,
    of: [SubSchema1, SubSchema2],
  },
});

const TestModel = mongoose.model("test", TestSchema);

const main = async () => {
  const mongod = await MongoMemoryServer.create();
  const uri = mongod.getUri();
  await mongoose.connect(uri);

  // This should produce an error, since price or description is required.
  await TestModel.create({
    product: {
      title: "string",
      arbitraryNeverSave: true,
      isThisSchema1: true,
      isThisSchema2: true,
    },
  });

  const data = await TestModel.find().lean();

  console.log(inspect(data, { depth: Infinity }));

  process.exit();
};

main();

Expected Behavior

The example should produce an error because the price or description should be defined.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions