Sarvesh Kulkarni
Sarvesh Kulkarni

Reputation: 981

Node JS: Type error: Cannot read property of undefined

I'm new to node.js. This is my first attempt. I'm building a small web application which displays the data from mongodb on the browser.

This is my index.js file

var express =  require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

Company = require('./models/company');

//connect to mongoose
mongoose.connect('mongodb://localhost/rs_active_members');
var db = mongoose.connection;

app.get('/',function(req, res) {
    res.send('Hello World!');
});

app.get('/api/companys', function(req, res) {
Company.getCompanys(function(err, companys) {
    if(err) {
        throw err;
    }
    res.json(companys);
   });
});
app.listen(8080);
console.log('Running on port 8000...');

This is my company.js file

var mongoose =  require('mongoose');

 //Generate Schema

 var companySchema = mongoose.Schema({
  name:{
       type: String,
       required: true
   },
  create_date:{
    type: Date,
    default: Date.now
   }

});

var Company = module.exports = mongoose.model('Company',companySchema)

// Get Companys

module.exports.getCompanys = function(callback, limit){
Company.find(callback).limit(limit);
}

The error is

TypeError: Cannot read property 'getCompanys' of undefined
at C:\Projects\rs_active_members\index.js:17:9
at Layer.handle [as handle_request] (C:\Projects\rs_active_members\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Projects\rs_active_members\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Projects\rs_active_members\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Projects\rs_active_members\node_modules\express\lib\router\layer.js:95:5)

Can anyone please help me where I'm going wrong? Thank you.

Upvotes: 0

Views: 1447

Answers (1)

Yash Sharma
Yash Sharma

Reputation: 293

I would restructure it as such:

Company.methods.getCompanies = (cb, limit) => {
  return this.model('Animal')
     .find({ type: this.type })
     .limit(limit)
     .exec(cb);
};

and then module.exports = mongoose.model('Company',companySchema) which will allow you to do this:

const Company = require('../models/company');
let newCompany = new Company(params);

Make sure to consult the mongoose documentation which is pretty good whenever you get stuck

Upvotes: 1

Related Questions