我正在我的数据库中创建一个新文档,在保存之前我想执行另一个操作。但是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();
});
});
答案 0 :(得分:0)
您必须使用new
关键字对您的模型进行实例化。引用Mongoose文档:
模型是从我们的模式定义编译的花哨构造函数。
let newProposal = new Proposal();