0

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 ?

2
  • 1
    Is it Controller.js or ProductController.js? Commented Oct 12, 2017 at 6:10
  • ProductController.js Commented Oct 12, 2017 at 6:56

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget that the controller.js file doesn't define Product anywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.