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));
});
I get this error:
MissingSchemaError: Schema hasn't been registered for model "Category".
Use mongoose.model(name, schema)
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.