感谢您的宝贵关注,我正在研究 MERN 堆栈并尝试做一些没有像我预期的那样工作的事情。(很抱歉,如果这是一个重复的问题,我是网络开发新手) .
来了
1.) 这个“潜在客户”模式包含许多字段,其中一个特殊字段是“状态”,当潜在客户的状态从“stageX”更改为“stageY”时,我希望该特定文档更新字段“stageYdate” '(最初为空)与当前日期。
2.)我希望无论以前存在的路由和请求如何,都会发生这种情况,该字段应该根据“状态”字段进行更新,因此模型级中间件(不确定它是否应该是文档级)
3.) 尝试对模拟架构/模型执行操作,但它也不起作用。
制作架构并导出模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ModelMiddlewareSchema = new mongoose.Schema({
stage: {
type: String
},
stageChangeDate:{
type: Date,
}
});
const ModelMiddleware = mongoose.model('ModelMiddleware', ModelMiddlewareSchema);
//Tried using middleware here on "ModelMiddleware", didn't work :(
module.exports = ModelMiddleware;
它给出了 ModelMiddleware.pre() 函数未定义的错误,所以我必须在路由中使用它
const ModelMiddleware = require('../models/modelMiddlewareCheck');
const express = require('express');
const router = express.Router();
const logMiddleware = async function(next) {
console.log(`Saving document ${this._id}`);
this.stage = 'stage2'
next();
};
ModelMiddleware.schema.pre('save', logMiddleware);
router.put('/', async (req, res) => {
try {
console.log('req received as', req.body);
const newDoc = new ModelMiddleware();
newDoc.stage = 'stage1';
await newDoc.save();
return res.status(200).send('stage1 created successfully');
} catch (err) {
console.log(err);
res.status(400).send('unsuccessful operation');
}
});
module.exports = router;
上面是模拟的,但我想做这样的事情
const stage_initial = this.stage;
const postStageCheck = function(next){
const stage_final = this.stage;
if(stage_initial==='stage1' && stage_final==='stage2'){
this.stageChangeDate = new Date();
this.save()
}
next();
}
ModelMiddleware.post('save', postStageCheck)
无论更新来自何处,都可以使用模型中间件来执行检查。
但是,我会使用 pre 而不是 post,然后您可以将 stageChangeDate 更新与新的状态更新捆绑在一起,这将减少对数据库的请求数量。
const schema = new Schema({ /* ... */ });
schema.pre('save', function(next) {
const currentStatus = this.status
if (this.isModified('status') {
const newStatus = this.status
if (currentStatus === 'x' && newStatus === 'y') {
this.stageChangeDate = new Date()
}
}
next();
});
总体走在正确的轨道上,但需要一些改变。
您想在保存文档之前对其进行修改,因此请使用
pre
中间件而不是 post
。 post
在文档保存后执行,因此为时已晚进行更改。
如果要与新状态进行比较,则需要手动存储之前的状态。您可以通过使用
pre
和 post
的组合来完成此操作。
// Pre-save middleware to store the stage
ModelMiddlewareSchema.pre('save', function(next) {
// Store the initial stage on the document
this._initialStage = this.stage;
next();
});
// Post-save middleware to check for change and update
ModelMiddlewareSchema.post('save', async function(doc) {
if (this._initialStage === 'stage1' && this.stage === 'stage2') {
// Update the stageChangeDate field
this.stageChangeDate = new Date();
// Save the updated document
await this.save();
}
});