mongoose.model 报错:MissingSchemaError: Schema hasn‘t been registered for model “Article“.

Error code


// 1. 引入mongoose模块
const mongoose = require('mongoose');
// 2.创建文章集合规则
const articleSchema = new mongoose.Schema({
    
    
    title: {
    
    
        type: String,
        maxlength: 20,
        minlength: 4,
        required: [true, '请填写文章标题 ']
    },
    author: {
    
    
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, '请传递作者']
    },
    publishDate: {
    
    
        type: Date,
        default: Date.now
    },
    cover: {
    
    
        type: String,
        default: null
    },
    content: {
    
    
        type: String
    }
})
// 3.根据规则创建集合
const Article = mongoose.model('Article')
// 4. 将集合规则做为模块成员进行导出
module.exports = {
    
    
    Article
}

Reason for error

At the beginning, only the collection rule was created, but it was not used when creating the collection.
So because mongoose.model() lacks the second parameter, it causes an error.

Solution

Add the second parameter of mongoose.model()

Modified code


// 1. 引入mongoose模块
const mongoose = require('mongoose');
// 2.创建文章集合规则
const articleSchema = new mongoose.Schema({
    
    
    title: {
    
    
        type: String,
        maxlength: 20,
        minlength: 4,
        required: [true, '请填写文章标题 ']
    },
    author: {
    
    
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, '请传递作者']
    },
    publishDate: {
    
    
        type: Date,
        default: Date.now
    },
    cover: {
    
    
        type: String,
        default: null
    },
    content: {
    
    
        type: String
    }
})
// 3.根据规则创建集合
const Article = mongoose.model('Article', articleSchema)
// 4. 将集合规则做为模块成员进行导出
module.exports = {
    
    
    Article
}

Self-motivation

A positive attitude and precise goal are the starting point for all achievements. I must keep my goals in mind, use a positive attitude, direct my thoughts, control my emotions, and control my destiny! ! !

Guess you like

Origin blog.csdn.net/weixin_50001396/article/details/112581136