javascript - Node.js,MongoDB 错误 - “消息”:“模式尚未注册模型 \“类别”。\n使用 mongoose.model(名称,模式)”
问题描述
我正在开发基于 Node.js、MongoDB 和 Express 的应用程序。我的目标是让 fetch API 系统正常工作。
当使用 Postman 检查我的状态时,“article.js”模型文件(在我的 localhost:3000/articles 中)的 GET 显示以下错误:
{
"error": {
"message": "Schema hasn't been registered for model \"Category\".\nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"
}
}
此错误会禁用 Postman 中我的文章或类别的显示,因为它们保存在 mongodb cloud的我的 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);
我在这里查找了过去的主题,例如这个- 但它并没有解决我的问题。
我应该怎么做才能修复我的代码?
是语法错误还是其他什么?
解决方案
代码似乎没问题
我在这里没有看到任何特定的错误
推荐阅读
- vb.net - GetResponse 不是 UWP 中 WebRequest 的成员
- android - 在根项目中找不到任务“组装”
- javascript - 在数组中查找对象的数组索引正在影响使用 grunt 的缩小和丑化
- android - 如何增加android中改造库的上传时间
- android - 找一个类似于网络音频API的android库
- javascript - 在 reactjs 中相对于其父级定位组件
- html - 图标真棒在同一行
- python - 网页抓取文本条
- ios - 单击按钮时将数据存储在 NSMutable 数组中
- javascript - 存储在 asp.net core 2.0 中的会话变量第一次给出 null 并且在刷新时工作正常