简体   繁体   English

猫鼬预保存方法不触发

[英]Mongoose Pre Save Method not triggering

I am creating a new document within my DB and before saving that I want to perform another action. 我正在数据库中创建一个新文档,并且在保存之前要执行其他操作。 but the pre save method does not execute. 但是pre save方法不执行。

My Code to Create New Document: 创建新文档的代码:

let create = (req, res) => {


   let newProposal = Proposal();

   newProposal.sector = req.body.sector;
   newProposal.client = req.body.client;
   newProposal.owner = req.body.owner;
   newProposal.proposalTitle = req.body.proposalTitle;
   newProposal.proposalRegion = req.body.proposalRegion;
   newProposal.clientContact = req.body.clientContact;


  newProposal.save()
    .then((savedProposal) => {return _updateUser(req.decoded._id, savedProposal)})
    .then(() => {return _checkClientExists(req.body.client)})
    .then((client) => {return _updateClientList(client, req.body)})
    .then(() => {res.json(newProposal)})
    .catch(err => {sendJsonResponse(res, 500, err)})
};

My Pre Save Code: 我的预保存代码:

proposalSchema.pre('save', function(next) {
   console.log("Does not work");
});

I have also tried using pre validate . 我也尝试过使用pre validate

What am I doing wrong? 我究竟做错了什么? I've been stuck for hours. 我已经被困了几个小时了。

Update: Proposal Schema Code: 更新:提案架构代码:

const proposalSchema = new mongoose.Schema({

proposalNo: Number,
proposalUrls: {type: String, default: 'none'},
proposalStatus: {type: String, default: 'live' ,set: toLower},
sector: {type: String, set: toLower},
client: {type: String, set: toLower},
owner: {type: String, set: toLower},
proposalTitle: {type: String, set: toLower},
proposalRegion: String,
clientContact: {type: String, set: toLower},


dateCreated: {type: Date, default: Date.now},

});

function toLower(data) {
   return data.toLowerCase();
}

proposalSchema.pre('save', function(next) {
   console.log("Does not work");
});

mongoose.model('Proposals', proposalSchema);

Update 2: 更新2:

const Counter = require('../models/counter');

proposalSchema.pre('save', function(next) {
    let doc = this;

    Counter.findByIdAndUpdate({_id: 'entityId'},{$inc: { seq: 1}},{"upsert": true,"new": true  }, function(error, counter)   {
        if(error) {
            return next(error);
        }

        doc.proposalNo = counter.seq;
        next();
    });
});

You must instantiate your model with the new keyword. 您必须使用new关键字实例化模型。 Citing the Mongoose documentation: 引用猫鼬文档:

Models are fancy constructors compiled from our Schema definitions. 模型是根据我们的Schema定义编译而成的精美构造函数。

let newProposal = new Proposal();

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

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