Sunday, 11 June 2017

Schema has not been registered error on population

When I'm trying to populate , this error is coming: " MissingSchemaError: Schema hasn't been registered for model "

My models: /models/course.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user')

var courseSchema = Schema({
    courseName:String,
    price:Number,
    type:String,
    _offeredBy:{type:Schema.Types.ObjectId,ref:User}
});

module.exports = mongoose.model("Course",courseSchem 

models/user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var findOrCreate = require('mongoose-findorcreate')
var Course = require('./course')

var userSchema = Schema({
    email:{type:String},
    password:{type:String},
    courseOffered:[{type:Schema.Types.ObjectId,ref:Course}]
});


module.exports = mongoose.model('User',userSchema);

routes/index.js

var Course = require('../models/course');
var User = require('../models/user');
var express = require('express');
var router = express.Router();

router.get('/user/profile',isLoggedIn,function(req,res,next){
res.render('user/profile',{csrfToken:req.csrfToken(),message:""})
});
router.post('/user/profile',isLoggedIn,function(req,res,next){
var courseInfo = req.body;
var newCourse = new Course();
newCourse.courseName = courseInfo.coursename;
newCourse.price = courseInfo.price;
newCourse.type = courseInfo.type;
newCourse._offeredBy = req.user;
newCourse.save(function(err,result){
if(err){
  res.redirect('/user/profile');
}
});
Course
.findOne({courseName:courseInfo.coursename})
.populate('_offeredBy')
.exec(function(err,course){
if(err){
  res.redirect('/user/profile');
}
});

});

Course is getting saved in the database, but the error is coming due to pouplating. I'm not writing the app.js, mongodb connections are made in app.js file.



via ASHUTOSH CHANDRA

No comments:

Post a Comment