Reputation: 1
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
Reputation: 938
Here's what's happening. There are multiple issues but we'll go through them.
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 belowProduct.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