mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

post middleware for 'updateOne' does not execute after executing this.findOne().clone() in pre middleware

Open ws-gregm opened this issue 8 months ago • 0 comments

Prerequisites

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

Mongoose version

8.13.2

Node.js version

20.18.2

MongoDB server version

8.0.4

Typescript version (if applicable)

5.8.3

Description

post-middleware for updateOne does not execute after retrieving the current object in pre-middleware.

Steps to Reproduce

Run the following. The following should appear in the output but it does not: 'at updateOne post -- schema'

import { Schema, model } from 'mongoose';
import mongoose from 'mongoose';

const schema = new Schema({
  name: String
});

schema.pre('updateOne', async function(next) {
  console.log('at updateOne pre -- schema');
  try {
    const result = await this.findOne().clone();
    console.log(result);
    next();
  } catch (err) {
    console.log(err);
    next(err);
  }
});

schema.post('updateOne', function() {
  console.log('at updateOne post -- schema');
});

const Test = model('Test', schema);

(async () => {
  await mongoose.connect('mongodb://localhost/test');
  await Test.create({ name: 'foo' });
  await Test.updateOne({ name: 'foo' }, { $set: { name: 'bar' } });
  mongoose.disconnect();
})();

Expected Behavior

The following should appear in the output: 'at updateOne post -- schema'

ws-gregm avatar Apr 25 '25 02:04 ws-gregm