Mongoose Schema 尚未注册模型 [英] Mongoose Schema hasn't been registered for model
问题描述
我正在学习平均堆栈,当我尝试使用
I'm learning the mean stack and when I try to start the server using
npm start
我收到一条异常消息:
schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)
这是我在/models/Posts.js 中的代码
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);
正如我所看到的,应该为模型Post"注册架构,但是什么可能导致抛出异常?
as I can see the schema should be registered for the model 'Post', but what can be possibly causing the exception to be thrown?
提前致谢.
这是异常错误
/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)
这里是带有 mongoose 初始化的 app.js 代码:
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');
行前:
app.use('/', routes);
推荐答案
这不是模型导出的问题.我遇到过同样的问题.
It's not an issue with model export. I had the same issue.
真正的问题是模型的 require 语句
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');
位于路由依赖项之下.只需将 mongoDB 依赖项移动到路由依赖项之上.它应该是这样的:
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();
这篇关于Mongoose Schema 尚未注册模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!