NodeJS +猫鼬:MissingSchemaError:尚未为模型"Category"注册模式. [英] NodeJS+Mongoose: MissingSchemaError: Schema hasn't been registered for model "Category"

查看:189
本文介绍了NodeJS +猫鼬:MissingSchemaError:尚未为模型"Category"注册模式.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个简单的博客,其中包含帖子和类别.当前可以将文章添加到父类别(将来,它们可能会添加到多个类别).一个类别有很多文章.这是我想出的:

I am trying to build a simple blog, where are posts and categories. Articles can be currently added to a parent category (in the future, they might be added to multiple categories). A category has many articles. This is what I came up with:

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;

Article.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;

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

When I try to load articles with their category names/details:

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的新手,所以我什至不确定这种模型结构是否适合我的情况(如果使用sub/embedded文档不是更好的选择).访客可以读取数据(文章),并且访客可以按类别过滤文章.

I am new to NoSQL, so I am not even sure if this model structure is appropriate for my case (if it would not be simply better to use sub/embedded document). The data (articles) would be read by visitors and visitors can filter articles by categories.

推荐答案

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

上一行说猫鼬,您声明的模型名称为categories

Above line says mongoose that the model you are declaring has the name categories

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

在这里您说的是categoryId引用的是Category模型!

Here you are saying categoryId is referencing to Category model!

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

So the issue is in your model name declaration. You should use same name in both lines.

这篇关于NodeJS +猫鼬:MissingSchemaError:尚未为模型"Category"注册模式.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆