Skip to content

Post middleware hooks not triggered when referenced from a model. #4955

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
EliKrumholz opened this issue Feb 5, 2017 · 3 comments
Closed

Comments

@EliKrumholz
Copy link

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Mongoose >=4.8.0 is not running post middleware in the following case.

If the current behavior is a bug, please provide the steps to reproduce.

var mongoose = require('mongoose');
var events = require('events');
var ThingEvents = new events.EventEmitter();

mongoose.connect(`mongodb://localhost:27017/mongoose-bug`);

var ThingSchema = new mongoose.Schema({
  name: String,
});

var Thing = mongoose.model('Thing', ThingSchema);

ThingEvents.on('test event', function(doc) {
  console.log('test event emitted');
});

Thing.schema.post('save', function(doc) {
  ThingEvents.emit('test event', doc);
});

Thing.create({name: 'test'});

What is the expected behavior?
Mongoose 4.7.9 logs test event emitted to the console, as expected.
Mongoose >=4.8.0 does not.

Please mention your node.js, mongoose and MongoDB version.
Node: 6.9.5
Mongoose: 4.8.1
MongoDB: 3.2.10

@EliKrumholz
Copy link
Author

Sorry, no need for an event emitter, here is a simpler example:

var mongoose = require('mongoose');

mongoose.connect(`mongodb://localhost:27017/mongoose-bug`);

var ThingSchema = new mongoose.Schema({
  name: String,
});

var Thing = mongoose.model('Thing', ThingSchema);

Thing.schema.post('save', function(doc) {
  console.log('Post hook triggered');
});

Thing.create({name: 'test'});

@EliKrumholz EliKrumholz changed the title Breaking change in post middleware API Post middleware hooks not triggered when referenced from a model. Feb 5, 2017
@sobafuchs
Copy link
Contributor

Hey @EliKrumholz, so mutating the underlying schema after the Thing model has been created by mongoose.model() isn't a supported behavior. Make sure you define all your hooks before calling mongoose.model().

@EliKrumholz
Copy link
Author

Got it, thanks for the reply @varunjayaraman.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants