猫鼬-释放保存钩不触发

时间:2019-05-21 15:48:51

标签: javascript node.js mongodb mongoose

这是我的帖子保存钩子:

profileSessionSchema.post('save',function(doc){
  console.log('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()
  })
})

如果有帮助,这是我的架构:

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);

我知道调用profile.save()方法是因为保存后我可以看到配置文件的更改。 我不明白自己所缺少的内容,我已经阅读了文档,看了有关该主题的其他帖子。

我还尝试使用3个参数(err, doc, next)定义后挂钩回调,并在回调定义的末尾调用next(),但这没什么区别。

感谢您的帮助。 干杯。

1 个答案:

答案 0 :(得分:0)

由于这篇文章,我终于找到了问题所在: https://github.com/Automattic/mongoose/issues/5073#issuecomment-287266986

最终,对于> 4.8的猫鼬,必须在创建模型之前设置钩子!

也就是说

// This must be define before mongoose.model(...)
profileSessionSchema.post('save',function(doc){
  console.log('POST SAVE HOOK')
})
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

谢谢

相关问题