Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schema hasn't been registered for model. Mongodb>Mongoose

Hi my code is shown below:

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Schema=mongoose.Schema
, ObjectId=Schema.ObjectId;

var BlogPost= new Schema({
    author:ObjectId,
    title:String,
    body:String,
    date:Date
    });

var myModel =mongoose.model('BlogPost','BlogPost');
console.log(myModel);

Need advise. I am always getting this exception.

  500 MissingSchemaError: Schema hasn't been registered for model "BlogPost".<br/>Use mongoose.model(name, schema)
like image 947
ftdeveloper Avatar asked Jan 11 '23 21:01

ftdeveloper


1 Answers

You're calling mongoose.model in a wrong way. You should pass a schema object object, but you're passing 'BlogPost' string instead. Try the following code:

var BlogPost= new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

var myModel = mongoose.model('BlogPost', BlogPost); // BlogPost is an object here

After that mongoose will create blogposts colection (lowercased and pluralized) in mongodb://localhost/test database. If you want to change collection name corresponding to your model, pass it as a thirs parameter:

var myModel = mongoose.model('BlogPost', BlogPost, 'BlogPost');
like image 80
Leonid Beschastny Avatar answered Jan 19 '23 13:01

Leonid Beschastny