1

I am new to Node and MongoDB. I am using mongoose to create schemas on Mongo. I have created two schemas in 1 models.js file as shown below

var mongoose = require('mongoose');

var postSchema =  new mongoose.Schema({
username: String,
text: String,
created_at: {type: Date, default: Date.now}
});

var userSchema =  new mongoose.Schema({
username: String,
password: String,
created_at: {type: Date, default: Date.now}
});





//declaring a model which has schema userSchema
mongoose.model("User", userSchema);
mongoose.model("Post", postSchema);

The problem is that my user schema is getting initialized and works fine. But the posts schema is a problem. This is the error that I get while starting the server:

C:\Users\rohit\Desktop\projects\chirp\module4\start\node_modules\mo
      throw new mongoose.Error.MissingSchemaError(name);
            ^
MissingSchemaError: Schema hasn't been registered for model "Post".

Here is my snippet from the api.js that actually calls post schema to make database queries

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
...
router.route('/posts')
.get (function(req, res){

    Post.find(function(err, data){
        if(err){
            return res.send(500, err)
        }

        return res.send(data)
    })

})

Here, is the code snippet from my auth.js file that uses the User Schema and it works fine

var LocalStrategy   = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Post = mongoose.model('Post');
module.exports = function(passport){

// Passport needs to be able to serialize and deserialize users to support     persistent login sessions
passport.serializeUser(function(user, done) {
    console.log('serializing user:',user._id);
    return done(null, user._id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user){
        if (err){
            return done(err, false)
        }

        if(!user){
            return done('User not found', false)
        }

        return done(user, true);
    })


});
rsisaudia
  • 67
  • 2
  • 8

1 Answers1

0

You are not loading your models (User and Post) in your models.js. Add the following lines after var mongoose = require('mongoose');:

var User = require('./models/user.js');  <-- type your user.js model path here
var Post = require('./models/post.js');  <-- type your post.js model path here
deChristo
  • 1,860
  • 2
  • 17
  • 29
  • But then why would it work for the user schema and nor for the Post schema? – rsisaudia Nov 26 '16 at 01:34
  • That's strange. Take a look at http://stackoverflow.com/questions/20832126/missingschemaerror-schema-hasnt-been-registered-for-model-user – deChristo Nov 26 '16 at 01:52