[英]Pass a Mongoose object thru middleware in Express
我已经建立了一个基本的记录器Mongoose DB对象,我希望该对象通过真实的中间件并随着应用程序的进展或特定条件进行更新/编辑。
记录器中间件。
function Logger(req, res, next) {
Logs.findOne({ip:func.GIP(req)},function (err, log){
if (err) console.log(err);
if (!log) {
var log = new Logs({ip: func.GIP(req), user: "anonymous"});
log.attempts = 1;
log.save();
next();
}
if (log.attempts > config.attempts) {
return res.status(403).send({
success: false
});
}
if (log.attempts <= config.attempts){
log.attempts += 1;
log.save();
next();
}
});
}
我的示例路线。
app.post("/example", Logger, function(req,res) {
if(!condition){
log.attempts = 0;
log.save();
}
});
我如何能够访问如上所述的log.save()
对象,而无需再次运行Logs.findOne({ip:f...
函数?
只需将log
变量添加到您的req
对象中:
function Logger(req, res, next) {
Logs.findOne({ip:func.GIP(req)},function (err, log){
if (err) console.log(err);
if (!log) {
var log = new Logs({ip: func.GIP(req), user: "anonymous"});
log.attempts = 1;
log.save();
req.log = log;
next();
}
if (log.attempts > config.attempts) {
return res.status(403).send({
success: false
});
}
if (log.attempts <= config.attempts){
log.attempts += 1;
log.save();
req.log = log;
next();
}
});
}
这样,您可以像这样访问它:
app.post("/example", Logger, function(req,res) {
if(!condition){
req.log.attempts = 0;
req.log.save();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.