nousernamesremained
nousernamesremained

Reputation: 25

mongoose and node error : Cannot call method 'model' of undefined

I tried following a tutorial on mongoose/mongodb with node and have fallen into issues trying to get express/node to res.send json documents from the collection.

The following code is producing errors when I try to access localhost:3000/mongodb

The database and collection exist. The collection has 3 documents.

app.js

/**
 * Module dependencies.
 */

var express = require('express');
var http    = require('http');
var path    = require('path');

var mongoose = require('mongoose');
var app = module.exports = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('html', require('hogan-express'));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

mongoose.connect('mongodb://localhost/xkayak');
var schema         = new mongoose.Schema({ username: 'string', email: 'string', password: 'string'});
var usercollection = mongoose.model('usercollection', schema);

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

require('./routes/index.js');

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

index.js --the routes file

var app = require('../app.js');

app.get('/mongodb', function(req, res) {
    app.mongoose.model('usercollection').find(function(err, usercollection) {
        res.send(usercollection);
    });
});

The error produced is:

500 TypeError: Cannot call method 'model' of undefined

What is wrong with my code? Did I set up the collection incorrectly? If I remove this code everything else works.

Upvotes: 1

Views: 1400

Answers (1)

Tony
Tony

Reputation: 2483

In your route, you are importing app. The problem is here:

var app = module.exports = express();

This means that when you import app.js you're going to get an instance of express, and not mongoose like you think when you do app.mongoose.model....

Consider:

app.js:

var app = express();
exports.express = app;
...
var mongoose = mongo.connect(...);
exports.mongoose = mongoose;

index.js:

app.express.get( ...
    app.mongoose.model(...);
);

Upvotes: 1

Related Questions