Reputation: 1468
Here is my post save hook :
profileSessionSchema.post('save',function(doc){
console.log('POST SAVE HOOK')
})
And here is the code that should fire the post save hook :
ProfileSession.findOne({prenom:'Georges'},function(err,profile){
//...
Realisation.findOne({},function(err,realDoc){
//...
profile.realisations.push(realDoc);
// And finally saving profile
profile.save()
})
})
And if it helps, here are my Schemas :
const profileSessionSchema = mongoose.Schema({
prenom: { type: String, required: [true,'ce champ est obligatoire'], trim:true},
realisations : [realisationSchema],
});
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);
const realisationSchema = mongoose.Schema({
profile_id :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
wall : { type: String, enum:walls, required:true},
pitch : { type: Number, min:1,max:maxWallsDiff, required:true,},
})
Realisation = mongoose.model('Realisation', realisationSchema);
I know the profile.save()
method is called because I can see the changes on the profile doc after saving.
I don't understand what I am missing, I've read the documentation, looked at the other posts dealing with this subject.
I have also tried to define the post hook callback with 3 arguments (err, doc, next)
, and calling next()
at the end of my callback definition, but it makes no difference.
Thank you for your help. Cheers.
Upvotes: 1
Views: 1965
Reputation: 1468
I eventually found what was the matter thanks to this post : https://github.com/Automattic/mongoose/issues/5073#issuecomment-287266986
It ends up that for mongoose > 4.8, hooks must be set BEFORE creating model !
That is to say
// This must be define before mongoose.model(...)
profileSessionSchema.post('save',function(doc){
console.log('POST SAVE HOOK')
})
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);
Thank you
Upvotes: 2