我正在学习平均堆栈,当我尝试使用
启动服务器时npm start
我得到一个异常(exception)说:
schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)
这是我在/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”注册,但是什么可能导致抛出异常?
提前致谢。
编辑:这是异常错误
/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 代码:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
行前:
app.use('/', routes);
最佳答案
这不是模型导出的问题。我遇到过同样的问题。
真正的问题是模型的 require 语句
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
低于路由依赖项。只需将 mongoDB 依赖项移到路由依赖项之上。它应该是这样的:
// 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();
https://stackoverflow.com/questions/26818071/