如何修改猫鼬中的现有模式?

How to modify existing schema in mongoose?

我正在为我的应用程序使用猫鼬。我有一些用于我的应用程序的简单模型,例如 Posts、用户和配置文件。我现在稍微更改了架构,但每次我尝试 运行 程序

时都会收到此错误
OverwriteModelError: Cannot overwrite `post` model once compiled.
[0]     at new OverwriteModelError (C:\Users\prate\PRACTISE CODE\Evaluate\node_modules\mongoose\lib\error\overwriteModel.js:20:11)
[0]     at Mongoose.model (C:\Users\prate\PRACTISE CODE\Evaluate\node_modules\mongoose\lib\index.js:472:13)
    at Object.<anonymous> (C:\Users\prate\PRACTISE CODE\Evaluate\models\Post.js:45:34)
[0]     at Module._compile (internal/modules/cjs/loader.js:701:30)
[0]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
[0]     at Module.load (internal/modules/cjs/loader.js:600:32)
[0]     at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
[0]     at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
[0]     at require (internal/modules/cjs/helpers.js:22:18)
[0]     at Object.<anonymous> (C:\Users\prate\PRACTISE CODE\Evaluate\routes\api\posts.js:8:14)
[0]     at Module._compile (internal/modules/cjs/loader.js:701:30)
[0]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
[0]     at Module.load (internal/modules/cjs/loader.js:600:32)
[0]     at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
[0]     at Function.Module._load (internal/modules/cjs/loader.js:531:3)

我已经尝试在 Whosebug 上搜索这个问题,有一个解决方案,那就是设置 'strict: false',但我不希望我的用户模型有垃圾值,我只想重新定义结构。

以前我的 Post 模型有这些字段:

const PostSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text: {
        type: String,
        required: true,
    },
    speechBody: {
        type: String

    },
    youtubeLink: {
        type: String
},
comments : [ {
    text: {
        type: String
}
}

],
});

现在我已经定义了一个名为 CommentSchema 的新架构,它具有喜欢和不喜欢以及许多其他功能。

因此现在我的模型看起来像这样:

const PostSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text: {
        type: String,
        required: true,
    },
    speechBody: {
        type: String

    },
    youtubeLink: {
        type: String
},
comments : [commentSchema],
});

CommentSchema 看起来像这样:

const CommentSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text: {
        type: String,
        required: true
    },
    name : {
        type: String,
    },
    avatar: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    }
});

谁能指导我如何修改 mongoose 中的架构?我不想使用 'strict: false',也不希望 mongodb 中已经存在的数据消失。我只想要具有这种新结构的相同旧数据。

您是否尝试过为 commentSchema 创建 ref 而不是使用子文档? 是这样的吗?

comments:[{ type: Schema.Types.ObjectId, ref: 'Comments' }]

这样您就可以拥有另一个模型和架构,而不会覆盖现有数据。