Node.js,MongoDB错误 - "message":"Schema hasn't been registered for model "类别\".nUse mongoose.mod



我正在开发一款基于Node.js、MongoDB和Express的应用程序。我的目标是让一个fetch API系统工作。

当使用Postman检查我的状态时,GET for"article.js"模型文件(在我的localhost:3000/articles中(显示以下错误:

{
"error": {
"message": "Schema hasn't been registered for model "Category".nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"
}
}

这个错误禁止在Postman中显示我的文章或类别,因为它们保存在MongoDB云中的MongoDB项目区域中。模型文件代码"article.js"如下:

const mongoose = require('mongoose');
const articleSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String, required: true },
description: { type: String, required: true },
content: { type: String, required: true },
categoryId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Category' }
});
module.exports = mongoose.model('Article', articleSchema);

该文件连接名为"articles.js"的控制器,具有以下相关代码:

const mongoose = require('mongoose');
const Article = require('../models/article');
const Category = require('../models/category');
module.exports = {
getAllArticles: (req, res) => {
Article.find().populate('categoryId', 'title').then((articles) => {    
res.status(200).json({
articles
})
}).catch(error => {
res.status(500).json({
error
})        
});
},
createArticle: (req, res) => {
const { title, description, content, categoryId } = req.body;
Category.findById(categoryId).then((category) => {
if (!category) {
return res.status(404).json({
message: 'Category not found'
})
}
const article = new Article({
_id: new mongoose.Types.ObjectId(),
title,
description,
content,
categoryId
});     
return article.save();
}).then(() => {
res.status(200).json({
message: 'Created article'
})
}).catch(error => {
res.status(500).json({
error
})        
});    
},
}

应用程序中的模型文件"category.js"代码如下:

const mongoose = require('mongoose');
const categorySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String, required: true },
description: { type: String, required: true }
});
module.exports = mongoose.model('Category', categorySchema);

我在这里查找了过去的话题,比如这个,但它并没有解决我的问题。

我应该怎么做才能修复我的代码?

是语法错误还是其他原因?

代码似乎可以

我在这里没有看到任何特定错误的

相关内容

最新更新