method not defined error in Node js express

Controller.js

<pre>

    exports.getProducts = function(callback)
    {
      Product.find({},function(err,products)
        {
            if(products === null)
            {
                console.log('Products not available in DB');                   
            }
            if(err) 
            {
                console.log(err);
                callback(err,null);
            }
            else{callback(null,products)};         
        });     
    }
    getProducts(function (err,data){
        if(err){console.error(err);}
        else{console.log(data);}
    });

</pre>

App.js

<pre>  

    var express = require('express');
    var app = express();
    var port = process.env.PORT || 3000;
    var bodyParser = require('body-parser');
    var cors = require('cors');
    var cookieParser = require('cookie-parser');
    var session = require('express-session');
    var morgan = require('morgan');
    app.use(cors());

    var Product = require('./server/controllers/ProductController');
    Product.save();
    console.log(Product.getProducts());

</pre>

I am trying to run getProducts() function from app.js, but it is failing by showing 'getProducts' is not defined Can anyone tell me the mistake I have done ?

Upvotes: 0

Views: 1661

Answers (1)

Shruggie
Shruggie

Reputation: 938

Here's what's happening. There are multiple issues but we'll go through them.

  1. You're requiring the ProductController.js, which runs all the code in that file. The first block of your controller sets a function, getProducts onto the exports object. The second part of that file attempts to invoke a function, called getProducts which is undefined. The function you're trying to invoke is defined as exports.getProducts, not getProducts, which is why you're getting the undefined error. But this is still wrong. More below
  2. In app.js, you're calling Product.getProducts(). This is exports.getProducts(). It takes a callback argument, which is not being provided in the call to getProducts in app.js.

Hope that helps you find a solution, good luck!

Upvotes: 2

Related Questions