Ayeye Brazo
Ayeye Brazo

Reputation: 3476

MIddleware run twice

I created a Middleware to get rid of my page request but it seems to run twice...

The first time it run has no error and second time has errors...

This is my code:

app.js file

app.get('/:slug', buildingController.findBuilding, buildingController.getBuilding);

buildings.js file

/**
 * Create a Middleware to Find Buildings
 */
exports.findBuilding = function(req, res, next) {
  if (!req.isAuthenticated()) {
    return res.redirect('/login');
  }

  Building.find(
    { "uniqueLink": req.params.slug,
        "$or": [
            { "_creator": req.user.id }
        ]
    }, function(err, building) {
        if (err) {
            return next(err);
        } else {
            if (building.length == 0 || building == null) {
                req.flash('errors', { msg: 'You are not allowed to see this building' });
                res.redirect('/buildings');
                next();
            } else {
                req.building = building[0];
                next();
            }
        }
    }
    );
};


/**
 * GET /:slug
 * Building home page.
 */

exports.getBuilding = function(req, res) {
    var building = req.building;
    res.render('building/home', {
    title: building.name,
    building: building
  });
};

This is the console output:

Express server listening on port 3000 in development mode
GET /my-slug 200 359.399 ms - -

Good, no errors but then:

TypeError: Cannot read property 'name' of undefined
[...etc...]

Where I'm failing? On my page everything works fine but I wish to no have errors...

I'm still learning Node.js.

Thanks.

Upvotes: 0

Views: 256

Answers (1)

Alexander Boychenko
Alexander Boychenko

Reputation: 286

 if (building.length == 0 || building == null) {

I think next() shouldn't be called in this case

Upvotes: 2

Related Questions