Reputation: 6567
I have set up a basic logger Mongoose DB objects that I want to pass true the middleware and update it/edit it as the app progresses or specific conditions.
Logger middleware.
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();
}
});
}
My example Route.
app.post("/example", Logger, function(req,res) {
if(!condition){
log.attempts = 0;
log.save();
}
});
How would I have access to the log.save()
objects as demonstrated above without running Logs.findOne({ip:f...
function again?
Upvotes: 0
Views: 795
Reputation: 14572
Just add the log
variable to your req
object:
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();
}
});
}
This way you can access it like this:
app.post("/example", Logger, function(req,res) {
if(!condition){
req.log.attempts = 0;
req.log.save();
}
});
Upvotes: 2