一尘不染

猫鼬模式尚未注册模型

node.js

我正在学习平均堆栈,当我尝试使用启动服务器时

npm start

我有一个例外说:

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)

这是带有猫鼬初始化的app.js代码:

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

前行:

app.use('/', routes);

阅读 256

收藏
2020-07-07

共1个答案

一尘不染

模型导出不是问题。我遇到过同样的问题。

真正的问题是需要模型声明

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();
2020-07-07