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

报错代码


// 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
}

报错原因

刚开始只是创建了集合规则但是在创建集合时却没有用到它
所以因为mongoose.model()缺少第二个参数,所以导致报错。

解决方法

补充上mongoose.model()的第二个参数

改后代码


// 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
}

自我激励

积极的心态和确切的’目标是走向一切成就的起点。我必须把自己的目标牢记在心里,用积极的心态,指挥我的思想,控制我的情绪,掌握自己的命运 !!!

猜你喜欢

转载自blog.csdn.net/weixin_50001396/article/details/112581136