【问题标题】:ExpressJS - duplicate key error collectionExpressJS - 重复键错误集合
【发布时间】:2018-11-26 01:42:12
【问题描述】:

当我使用我的数据库中存在的类别创建一个新事件时,我遇到了这个错误的问题,例如,我创建了一个类别为“javascript”的事件并将其保存到数据库,然后我尝试创建一个新事件使用“javascript、html、css”类别,然后我收到此错误duplicate key error collection

所以我的事件架构是这样的:

    const EventSchema = new Schema({
    title: {
        type: String,
        required: true,
        min: 3,
        max: 100
    },
    featuredImage: {
        type: Object,
    },
    from: {
        type: Date,
        required: true
    },
    to: {
        type: Date,
        required: true
    },
    location: {
        name: {
            type: String
        },
        address: {
            type: Object
        }
    },
    description: {
        type: String
    },
    categories: {
        type: Array,
        trim: true
    },
    featured: {
        type: Boolean
    },
    created_by: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    slug: {
        type: String,
        default: null
    },
    registration: {
        type: Boolean
    },
    tickets: [],
    allday: {
        type: Boolean
    },
    speakers: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }],
    attendees: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }],
    comments: [CommentSchema]
}, {
    timestamps: true,
    usePushEach: true
});

所以基本上发送字符串数组,我得到了这个错误。

【问题讨论】:

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您可能在categories 上使用unique 标志定义了一些索引

您可以使用db.events.getIndexes() 列出现有索引。

您可以删除并重新创建罪魁祸首(小心):

> db.events.dropIndex({categories:1})
> db.events.ensureIndex({categories:1},{sparse:true})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2021-09-19
    • 2021-03-04
    • 2018-07-21
    • 2019-01-05
    • 2021-09-02
    • 2018-07-29
    相关资源
    最近更新 更多