Mongoose Pre Save方法不会触发

问题描述 投票:0回答:1

我正在我的数据库中创建一个新文档,在保存之前我想执行另一个操作。但是pre save方法没有执行。

我的代码来创建新文档:

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

我的预存代码:

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

我也尝试过使用pre validate

我究竟做错了什么?我被困了几个小时。

更新:提案架构代码:

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);

更新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();
    });
});
javascript node.js mongodb mongoose
1个回答
0
投票

您必须使用new关键字实例化您的模型。引用Mongoose文档:

模型是从我们的模式定义编译的花哨构造函数。

let newProposal = new Proposal();
© www.soinside.com 2019 - 2024. All rights reserved.