NodeJS+Mongoose:MissingSchemaError:尚未为模型"Category"注册架构



我正在尝试建立一个简单的博客,其中有帖子和类别。文章当前可以添加到父类别(将来可能会将其添加到多个类别(。一个类别有许多文章。这就是我想出的:

类别.js

const CategorySchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
user: { // I wanted to know what user created the category
type: mongoose.Schema.Types.ObjectId, 
ref: 'User'
}
},
{
timestamps: true
});
const Category = mongoose.model('categories', CategorySchema);
module.exports = Category;

文章.js

const ArticleSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
article_body: {
type: String,
trim: true
},
userId: { 
type: mongoose.Schema.Types.ObjectId, 
ref: 'User'
},
categoryId: { 
type: mongoose.Schema.Types.ObjectId, 
ref: 'Category'
}
},
{
timestamps: true
});
const Article = mongoose.model('articles', ArticleSchema);
module.exports = Article;

当我尝试加载带有类别名称/详细信息的文章时:

Article.find({}).populate('categoryId').sort('name').exec(function(err, articles) {
if(err) throw err;
res.send(JSON.stringify(articles));
});

我收到此错误:

MissingSchemaError: Schema hasn't been registered for model "Category".
Use mongoose.model(name, schema)

我是NoSQL的新手,所以我甚至不确定这种模型结构是否适合我的情况(如果使用子/嵌入式文档不是更好的话(。数据(文章(将由访问者读取,访问者可以按类别过滤文章。

const Category = mongoose.model('categories', CategorySchema);

上行说猫鼬,您声明的模型具有名称categories

categoryId: { 
type: mongoose.Schema.Types.ObjectId, 
ref: 'Category' // this name does not match to 'categories'
}

在这里你说categoryId指的是Category模型!

因此,问题出在您的模型名称声明中。应在两行中使用相同的名称。

最新更新