Node JS:类型错误:无法读取undefined的属性

时间:2017-05-31 23:07:13

标签: node.js mongodb express mongoose mongoose-schema

我是node.js的新手。这是我的第一次尝试。我正在构建一个小型Web应用程序,它在浏览器上显示来自mongodb的数据。

这是我的index.js文件

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...');

这是我的company.js文件

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);
}

错误是

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)

任何人都可以在我出错的地方帮助我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

我会这样重组:

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

然后module.exports = mongoose.model('Company',companySchema) 这将允许你这样做:

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

请务必查阅mongoose文档,这个文件非常好,无论何时卡住