Do you want to request a feature or report a bug?
Report a bug
What is the current behavior?
Hooks are not firing
If the current behavior is a bug, please provide the steps to reproduce.
const newEntity = new Entity(req.body);
newEntity.save()
FromSchema.pre('save', function(next) {
console.log('pre save..');
next();
});
What is the expected behavior?
When I save the entity, I should see the log
Please mention your node.js, mongoose and MongoDB version.
Mongoose: 4.9.0
Node: 6.9.5
MongoDb 3.4.2
+1
I have determined that this problem appeared since version 4.8.0. Why hadn't anyone noticed it before?
+1
Took me a while to figure out what's going on as well... I am using 4.8.3
So, I'm researched this issue and i found trouble. It reproduce code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
name: String
});
const Entity = mongoose.model('Entity', schema); // create model before hooks
schema.pre('validate', function(next) {
console.log('first pre validate...');
next();
});
schema.pre('save', function(next) {
console.log('first pre save...');
next();
});
schema.pre('save', function(next) {
console.log('second pre save...');
next();
});
schema.post('save', function() {
console.log('post save');
});
const entity = new Entity({name: 'Foo'});
mongoose.connect('mongodb://localhost/mongoose')
.then(() => entity.save())
.then(() => entity.set('name', 'Bar').save())
.then(() => Entity.findOne(entity._id))
.then(fromDb => fromDb.set('name', 'WAT').save())
.then(() => mongoose.disconnect())
.catch(reason => (console.log(reason), mongoose.disconnect()));
we can set hooks after create model in mongoose <4.8, but in mongoose >4.8 we cannot do it.
This is a breaking change and 4.8 should be called name 5.0
@vkarpov15
@chetverikov this was never a supported behavior, we just enforced it after 4.8. Always set your hooks before calling mongoose.model()
@varunjayaraman maybe it would be a good idea to clarify this in documentation regarding hooks or else someone might end up pulling his hair trying to figure out what's going on.
Is there a workaround for this change of behavior? I currently have a separate module for my mongoose docs and apply the needed hooks for the specific app needs after the fact.
@blyork unfortunately not. However, if you have a separate module, I'd recommend you have that module export schemas and then attach hooks to those schemas in your apps.
@chetverikov this was never a supported behavior, we just enforced it after 4.8. Always set your hooks before calling
mongoose.model()
What is the point of that? It took me half a day to find such change!