javascript - 用mongoose Model.create(doc,cb)无效

 守护雪天_使0062_423 发布于 2022-11-17 22:43

如题,跟踪进不了回调,在sechma的pre save hook能跟踪到确实执行到了pre save,但是没有保存到数据库。新添加了post save hook 但log中没有输出,说明save没执行完成。

  1. sechma

var mySchema = new mongoose.Schema({
    employee_name: { type: String },
    employee_no: { type: String },
    month: { type: Number },
    date: [String],
    lastModifyDate: Date
});
mySchema .pre("save", function (next) {    
    this.lastModifyDate = Date.now();
    console.log("save one:", this);
});
  1. 业务层

var createPromise = function (doc,newData) {
    return new Promise(function (fulfill, reject) {
    ...省略doc的校验 doc为上个promise传入的查询结果
    myModel.create({
                    employee_name: newData.emp_name,
                    employee_no: newData.emp_no,
                    month: newData.month,
                    overtime_date: newData.addDates.rmArr(newData.rmDates)
                }, function (err, res) {
                    if (err) return reject(err);
                    return fulfill(res);
                });
});
createPromise
.then(function(res){...})
.catch(...)

现在跟踪进入到create后没有执行then或者catch中的console.log

2 个回答
  • 确实在pre hook这里忘记执行next();导致保存中断。
    在补上next()后问题解决。

    2022-11-17 22:49 回答
  • mySchema .pre("save", function (next) {    
        this.lastModifyDate = Date.now();
        console.log("save one:", this);
        next();
    });
    2022-11-17 22:49 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有