【问题标题】:Pass a Mongoose object thru middleware in Express通过 Express 中的中间件传递 Mongoose 对象
【发布时间】:2015-05-24 23:20:45
【问题描述】:

我已经设置了一个基本的记录器 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();
    }
});

如何在不再次运行Logs.findOne({ip:f... 函数的情况下访问上述log.save() 对象?

【问题讨论】:

    标签: node.js mongodb logging express


    【解决方案1】:

    只需将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();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多