Jorge Barbi
Jorge Barbi

Reputation: 5

Why can't I separate the creation of the function and the export when using Node/Expree and Pug?

In an app built using Node/Express, MongoDB/Mongoose and Pug, I have this controller function JS file named indexController2.js where I am exporting a funcioned named index.

I know that it will work perfectly if I write exports.index... However, I'd like to know why can't I separate the creation of the funciont form the export, just like shown in the below?

(Node returns an error of Route.get() requires a callback function but got a [object Undefined])

function index(req, res) {
    Livro.countDocuments({}, function(err, results){
        if (err){
            res.render('livrariaIndex2', {title: 'Livraria JBM Home', count: 'Erro!!!!'});        
        } else {
            res.render('livrariaIndex2', {title: 'Livraria JBM Home', count: results});
        }
    })
}

exports.index;

Upvotes: 0

Views: 30

Answers (1)

jfriend00
jfriend00

Reputation: 707158

To successfully export your index function as the index export name, you must assign the index function to be an index property of the exports object.

So, you should be using:

exports.index = index;

Just executing this by itself:

exports.index;

does not do anything. It doesn't assign anything to anything.

Upvotes: 0

Related Questions