Explore Courses Blog Tutorials Interview Questions
0 votes
in Web Technology by (47.6k points)

I'm learning 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 can be possibly causing the exception to be thrown?

Thanks in advance.

2 Answers

0 votes
by (106k points)

The real problem here is that require statements for the models

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


0 votes
by (108k points)

You have to simply move the MongoDB dependencies above the routes dependencies like the following:

var mongoose = require('mongoose');




var routes = require('./routes/index');

var users = require('./routes/users');

var app = express();

Browse Categories