[英]Why mongoose middleware “pre” remove with { query: true } is not called?
I'm a bit stuck on this problem. 我对此问题有些困惑。 I have read all the mongoose documentation about middleware and some stackoverflow issue and was unable to find-out how to solve my problem without duplicating queries (find then remove).
我已经阅读了所有有关中间件的猫鼬文档和一些stackoverflow问题,并且无法找到如何解决我的问题而不重复查询(查找然后删除)。
Normally, pre middleware on remove will not fire when call from Model and not from document. 通常,从模型而不是从文档调用时,在remove上的中间件不会触发。 But according with the doc , if I add {query: true}, my function will be called from model query.
但是根据文档 ,如果我添加{query:true},则将从模型查询中调用我的函数。
I use the latest monngoose version (5.4.16) 我使用最新的猫鼬版本(5.4.16)
Here is my code. 这是我的代码。
let mySchema= new mongoose.Schema({
name: String,
comment: String
}, { usePushEach: true });
mySchema.pre('remove', { document: true }, function() {
console.log('remove document');
});
mySchema.pre('remove', { query: true }, function() {
console.log('remove');
});
const MyModel = mongoose.model('MyModel', mySchema);
And the call here 还有这里的电话
MyModel.deleteOne({ _id: modelId }, (errorRm) => {
if (errorRm) {
return res.json({ success: false, message: `${errorRm.message}` });
}
return res.json({ success: true, message: 'Model successfully removed' });
});
The model is successfully removed but nothing is logged from the "pre" functions... 该模型已成功删除,但是“ pre”功能未记录任何内容。
Any help would be welcomed. 任何帮助都将受到欢迎。
It's because you're using MyModel.deleteOne() . 这是因为您正在使用MyModel.deleteOne() 。 Use MyModel.remove() and it will work.
使用MyModel.remove() ,它将起作用。
Acoording to the documentation: 根据文档:
You can pass options to Schema.pre() and Schema.post() to switch whether Mongoose calls your remove() hook for Document.remove() or Model.remove():
您可以将选项传递给Schema.pre()和Schema.post()来切换是猫鼬为Document.remove()还是Model.remove()调用remove()钩子:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.