themollusk
themollusk

Reputation: 440

Express Middleware running multiple times during MongoDB query

I'm running the below route to retrieve a list of projects.

app.get('/test', function(request, response){
    Project.find({}, function(err, projects) {
      if (err) throw err;
       response.render(__dirname + '/app/test', projects);
    });
});

Everything works fine, but I noticed when I add this middleware:

app.use(function(req, res, next){
    console.log('Things!');
    next();
});

I log "Things!" 7 times (the amount of results returned by the query).

Is middleware mean't to run for each result. I feel like I'm doing something wrong. I'm still learning Node and Express and trying to not pick up bad habits...

Cheers

Upvotes: 4

Views: 1341

Answers (1)

Vishnu
Vishnu

Reputation: 12303

app.use(function(req, res, next){
    console.log(req.url);
    next();
});

Change your middleware as mentioned above and check the output. It helps for debugging. Add the output to the question.

Upvotes: 3

Related Questions