Search code examples
node.jsmongodbmongoose

Mongoose Schema hasn't been registered for model


I'm using the MEAN stack and when I try to start the server using npm start, I get an exception saying that:

schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)

Here is my code inside /models/Posts.js:

var mongoose = require('mongoose');

var PostSchema = new mongoose.Schema({
    title: String,
    link: String, 
    upvotes: { type: Number, default: 0 },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

mongoose.model('Post', PostSchema);

as I can see the schema should be registered for the model 'Post', but what is causing the exception to be thrown?

Edit: Here's the exception error:

/home/me/Documents/projects/personal/flapper-news/node_modules/mongoose/lib/index.js:323
  throw new mongoose.Error.MissingSchemaError(name);
        ^
MissingSchemaError: Schema hasn't been registered for model "Post".
Use mongoose.model(name, schema)

and here's the app.js code with the mongoose initialization:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');

before the line:

app.use('/', routes);

Solution

  • It's not an issue with model export. I had the same issue.

    The real issue is that require statements for the models

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/news');
    require('./models/Posts');
    require('./models/Comments');
    

    were below the routes dependencies. Simply move the mongoDB dependencies above the routes dependencies. This is what it should look like:

    // MongoDB
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/news');
    require('./models/Posts');
    require('./models/Comments');
    
    var routes = require('./routes/index');
    var users = require('./routes/users');
    
    var app = express();