[英]Mongoose pre/post middleware not getting called for model.save
I looked at the documentation and can't figure out the problem.我查看了文档,无法找出问题所在。 The pre & post middleware doesn't seem to be working.
前后中间件似乎没有工作。 I have updated node and all of my modules.
我已经更新了节点和我的所有模块。
// schema.js
const schema = mongoose.Schema(...)
schema.pre('save', function(next) {
console.log('pre save') // I don't see this in the console
next()
})
schema.post('save', function(next) {
console.log('post save') // I don't see this in the console
next()
})
module.exports = ({
MySchema: mongoose.model('MySchema', schema)
})
// api.js
app.post('/users', (req, res) => {
const model = new MySchema(...)
model.save().then(() => {
res.sendStatus(201)
})
}
I figured it out.我想到了。 I wasn't filling all of the
required
fields, and I was going planning on doing so in the pre.save
middleware function.我没有填写所有
required
字段,我打算在pre.save
中间件 function 中填写。 I was getting an error "Path fieldName
is required" but there was no stack trace, so I didn't know that the issue was with the validate
middleware.我收到错误“需要路径
fieldName
”但没有堆栈跟踪,所以我不知道问题出在validate
中间件上。 I assumed the error was happening during the save
method.我认为错误是在
save
方法期间发生的。
TL;DR: The methods in order are init, validate, and save. TL;DR:按顺序排列的方法是初始化、验证和保存。 See Save/Validate Hooks in the documentation .
请参阅文档中的保存/验证挂钩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.