首页 > 解决方案 > 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);

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

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

是语法错误还是其他什么?

标签: javascriptnode.jsmongodbapimongoose-schema

解决方案


代码似乎没问题

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


推荐阅读