簡體   English   中英

Node.js, MongoDB 錯誤 - "message": "Schema 尚未為模型 \\"Category\\" 注冊。\\n使用 mongoose.model(name, schema)"

[英]Node.js, MongoDB error - "message": "Schema hasn't been registered for model \"Category\".\nUse mongoose.model(name, schema)"

我正在開發基於 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);

我在這里查找了過去的主題,例如這個- 但它並沒有解決我的問題。

我應該怎么做才能修復我的代碼?

這是語法錯誤還是其他什么?

代碼似乎沒問題

我在這里沒有看到任何特定的錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM