Mean Stack MissingSchemaError: Schema hasn't been registered for model "User"

1.2k views Asked by At

I have tried many solutions given on stack overflow but nothing worked in my case... here is my code... server.js which is entry point of my application.

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var config = require('./config/config'),
    mongoose = require('./config/mongoose'),
    passport = require('./config/passport'),
    express = require('./config/express');
var passport = passport();
var db = mongoose(),
    app = express();

app.listen(config.port);

module.exports = app;
console.log(process.env.NODE_ENV  + ' server running at http://localhost:' + config.port);

My config.js is

module.exports = require('./env/' + process.env.NODE_ENV + '.js');

Mongoos.js

var config = require('./config'),
    mongoose = require('mongoose');

module.exports = function() {
    var db = mongoose.connect(config.db);
    require('../app/models/user.server.model');
    return db;
};

Passport.js

var mongoose = require('mongoose');
var passport = require('passport');
var User = mongoose.model('User');

module.exports = function() {

    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findOne(
            {_id: id},
            '-password',
            function(err, user) {
                done(err, user);
            }
        );
    });

    require('./strategies/local.js')();
};

Express.js

var config = require('./config'),
    express = require('express'),
    bodyParser = require('body-parser'),
    passport = require('passport');



module.exports = function() {
    var app = express();
    var session = require('express-session');


    var flash = require('connect-flash');

    app.use(flash());

    app.use(session({
        saveUninitialized: true,
        resave: true,
        secret: 'OurSuperSecretCookieSecret'
    }));

    app.use(bodyParser.urlencoded({
        extended: true
    }));

    //use this code before any route definitions
    app.use(passport.initialize());
    app.use(passport.session());

    app.use(bodyParser.json());

    app.set('views', './app/views');
    app.set('view engine', 'ejs');

    require('../app/routes/index.server.routes.js')(app);
    require('../app/routes/users.server.routes.js')(app);

    app.use(express.static('./public'));

    return app;
};

and finally modal file users.server.model.js is here.

var mongoose = require('mongoose'),
    crypto = require('crypto'),
    Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: String,
    email: String,
    username: {
        type: String,
        trim: true,
        unique: true
    },
    password: String,
    provider: String,
    providerId: String,
    providerData: {},
    todos: {}//we will use this in the next tutorial to store TODOs
});

UserSchema.pre('save',
    function(next) {
        if (this.password) {
            var md5 = crypto.createHash('md5');
            this.password = md5.update(this.password).digest('hex');
        }

        next();
    }
);

UserSchema.methods.authenticate = function(password) {
    var md5 = crypto.createHash('md5');
    md5 = md5.update(password).digest('hex');

    return this.password === md5;
};

UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
    var _this = this;
    var possibleUsername = username + (suffix || '');

    _this.findOne(
        {username: possibleUsername},
        function(err, user) {
            if (!err) {
                if (!user) {
                    callback(possibleUsername);
                }
                else {
                    return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
                }
            }
            else {
                callback(null);
            }
        }
    );
};

var User = mongoose.model('User', UserSchema);
exports = User;

at the last two lines i have tried different approaches I also tried simply mongoose.model('User', UserSchema); this line but doesn't worked. I am using this tutorial https://hackhands.com/mongodb-crud-mvc-way-with-passport-authentication/

1

There are 1 answers

1
Yuri Zarubin On BEST ANSWER

You are loading your /config/passport before the model is registering. You need to require the file that registers your model first. So something like this:

var config = require('./config/config'),
    mongoose = require('./config/mongoose'),
    // require the file that has your model
    model = require('./path/to/users.server.model'),
    passport = require('./config/passport'),
    express = require('./config/express');
var passport = passport();
var db = mongoose(),
    app = express();

Alternatively, you can include that file inside /config/passport.js before calling var User = mongoose.model('User');