1

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.

3
  • 1
    Could you post your require('mongoose') part of the source? Commented Aug 8, 2014 at 20:15
  • To piggy back on @staaar, you probably only need mongoose.model('usercollection'). But we can't be sure until we see how you're including mongoose. Commented Aug 8, 2014 at 20:16
  • @staaar and Tony I updated the question Commented Aug 8, 2014 at 20:21

1 Answer 1

1

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(...);
);
Sign up to request clarification or add additional context in comments.

Comments

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.