Mongoose Schema hasn't been registered for mod

2019-01-08 14:46发布

问题:

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.

Edit: Here's the exception error

/home/arash/Documents/projects/personal/flapper-news/node_modules/mongoose/lib/index.js:323
  throw new mongoose.Error.MissingSchemaError(name);
        ^
MissingSchemaError: Schema hasn't been registered for model "Post".
Use mongoose.model(name, schema)

and here's the app.js code with the mongoose initialization:

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

before the line:

app.use('/', routes);

回答1:

It's not an issue with model export. I had the same issue.

The real issue is that require statements for the models

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

were below the routes dependencies. Simply move the mongoDB dependencies above the routes dependencies. This is what it should look like:

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

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

var app = express();


回答2:

If someone coudn't fix it with the approach of the correct answer (like me), try to look at the creation of the schema. I wrote the 'ref' as 'User', but the correct was 'user'.

Wrong:

createdBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
}

Correct:

createdBy: {
    type: Schema.Types.ObjectId,
    ref: 'user'
}


回答3:

IF YOU USE MULTIPLE mongoDB CONNECTIONS


beware that when using .populate() you MUST provide the model as mongoose will only "find" models on the same connection. ie where:

var db1 = mongoose.createConnection('mongodb://localhost:27017/gh3639');
var db2 = mongoose.createConnection('mongodb://localhost:27017/gh3639_2');
var userSchema = mongoose.Schema({
  "name": String,
  "email": String
});

var customerSchema = mongoose.Schema({
  "name" : { type: String },
  "email" : [ String ],
  "created_by" : { type: mongoose.Schema.Types.ObjectId, ref: 'users' },
});

var User = db1.model('users', userSchema);
var Customer = db2.model('customers', customerSchema);

Correct:

Customer.findOne({}).populate('created_by', 'name email', User)

or

Customer.findOne({}).populate({ path: 'created_by', model: User })

Incorrect (produces "schema hasn't been registered for model" error):

Customer.findOne({}).populate('created_by');


回答4:

Elaborating on Rafael Grilli's answer above,

Correct:

var HouseSchema = new mongoose.Schema({
  date: {type: Date, default:Date.now},
  floorplan: String,
  name:String,
  house_id:String,
  addressLine1:String,
  addressLine2:String,
  city:String,
  postCode:String,
  _locks:[{type: Schema.Types.ObjectId, ref: 'xxx'}] //ref here refers to the first parameter passed into mongoose.model()
});
var House = mongoose.model('xxx', HouseSchema, 'houseschemas');


回答5:

You should also check that you don't have dirty data in your database. I ended up with a document containing the lowercased version of the referenced model (user instead of User). This causes the error and is incredibly hard to track down.

Easy to fix with a quick mongo query:

db.model.updateMany({ approvedByKind: 'user' }, { $set: { approvedByKind: 'User' } })