簡體   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