Mongoose报错save()不再支持回调,post('save')中间件无日志输出求助
Mongoose问题解决方案:save()回调报错与post('save')中间件不触发
问题1:save()不再接受回调函数
Mongoose 6.x及以上版本已移除save()方法的回调参数支持,原回调写法会触发报错。需改用Promise链式调用或async/await语法:
- Promise写法:
h.save() .then(() => console.log("logged")) .catch(err => console.error(err));
- async/await写法(需在async函数内执行):
async function createHuman() { try { await h.save(); console.log("logged"); } catch (err) { console.error(err); } } createHuman();
问题2:post('save')中间件不触发
你当前代码的逻辑顺序错误:先创建了Human模型,再给schema绑定post中间件。Mongoose在创建模型时会固化schema的结构与中间件配置,后续添加的中间件无法生效。
解决方法:调整代码顺序,先给schema添加中间件,再创建模型。
完整修正代码
const mongoose = require('mongoose'); // 1. 定义Schema const humanSchema = new mongoose.Schema({ name: String, }); // 2. 绑定post('save')中间件(必须在创建模型前执行) humanSchema.post('save', function(docs, next) { console.log("A save function occured"); next(); }); // 3. 创建模型 const Human = mongoose.model('human', humanSchema); // 4. 调用save() const h = new Human({name:"john"}); h.save() .then(() => console.log("logged")) .catch(err => console.error(err));
以上修改后,post('save')中间件会正常打印日志,同时save()方法也不再触发回调报错。
内容的提问来源于stack exchange,提问作者Lipin Kariappa
相关产品推荐
相关产品推荐

