Skip to content

Schema.clone() drops $timestamps, so embedded discriminators with a timestamped child schema throw on save #16650

Closed

Description

@Oleksii-Pavliuk

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.11.4

Node.js version

24

MongoDB server version

8

Typescript version (if applicable)

No response

Description

If a schema contains a child schema with timestamps: true, Mongoose adds $timestamps and a timestampsPreSave hook to the parent. clone() copies the hook but not $timestamps, so saving a document built from the clone throws:

TypeError: Cannot destructure property 'createdAt' of 'schema.$timestamps' as it is undefined.
    at EmbeddedDocument.timestampsPreSave (lib/helpers/timestamps/setupTimestamps.js:96:11)

Steps to Reproduce

const child = new Schema({ name: String }, { timestamps: true });
const base = new Schema({ kind: String }, { discriminatorKey: 'kind' });
const schema = new Schema({ items: [base] });
schema.path('items').discriminator('WithChild', new Schema({ child }));
const Test = mongoose.model('Test', schema);
await Test.create({ items: [{ kind: 'WithChild', child: { name: 'foo' } }] }); // throws

Expected Behavior

The clone saves like the original.

Activity

  1. added this to the 9.11.5 milestone on Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions