繁体   English   中英

Mongoose 前/后中间件没有被调用 model.save

[英]Mongoose pre/post middleware not getting called for model.save

我查看了文档,无法找出问题所在。 前后中间件似乎没有工作。 我已经更新了节点和我的所有模块。

// 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)
    })
}

我想到了。 我没有填写所有required字段,我打算在pre.save中间件 function 中填写。 我收到错误“需要路径fieldName ”但没有堆栈跟踪,所以我不知道问题出在validate中间件上。 我认为错误是在save方法期间发生的。

TL;DR:按顺序排列的方法是初始化、验证和保存。 请参阅文档中的保存/验证挂钩

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM