Skip to content

[Bug] Subdoc save hooks do not receive options #15920

@AbdelrahmanHafez

Description

@AbdelrahmanHafez

Prerequisites

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

Issue

Summary

Subdocument pre('save') hooks do not receive the options argument, even though the docs show this is supported.

Expected Behavior

Save hooks should receive options according to the docs, should work for subdocuments as well.

userSchema.pre('save', function(options) {
  options.validateModifiedOnly; // true
});

await doc.save({ validateModifiedOnly: true });

Actual Behavior

Subdocument save hooks receive undefined instead of the options object.

const childSchema = new Schema({ name: String });
childSchema.pre('save', function(options) {
  console.log(options); // undefined
});

const parentSchema = new Schema({ child: childSchema });
const Parent = mongoose.model('Parent', parentSchema);

await new Parent({ child: { name: 'test' } }).save({ customOption: true });
// Child hook logs: undefined

Repro script

it('pre save hooks on subdocs receive save options', async function() {
  // Arrange
  let receivedOptions = null;

  const addressSchema = new Schema({ city: String });
  addressSchema.pre('save', function(options) {
    receivedOptions = options;
  });

  const userSchema = new Schema({
    name: String,
    address: addressSchema
  });

  const User = db.model('User', userSchema);

  // Act
  const user = new User({ name: 'John', address: { city: 'New York' } });
  await user.save({ customOption: 'test123' });

  // Assert
  assert.ok(receivedOptions, 'Subdoc pre save hook should receive options');
  assert.strictEqual(receivedOptions.customOption, 'test123');
});
``

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