1

I have problem with this error when I am creating a new event with category which exists in my database, for example I created an event with category "javascript" and save it to db, and then i tried to create a new event with categories "javascript, html, css" and then i got this error duplicate key error collection

So my schema for event is this:

    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
});

So basically sending array of strings and i got this error.

Krešimir Galić
  • 311
  • 2
  • 14
  • 1
    Were the rest of the fields unique? Look at this https://stackoverflow.com/questions/24430220/e11000-duplicate-key-error-index-in-mongodb-mongoose – Aviad Nov 25 '18 at 16:46
  • please give an example of the two events you created (the one that was created, and the one that threw the error) – OzW Nov 25 '18 at 17:20

1 Answers1

0

You probably have some index defined on categories with the unique flag.

You can list the existing indexes with db.events.getIndexes().

You could drop and recreate the culprit (be careful):

> db.events.dropIndex({categories:1})
> db.events.ensureIndex({categories:1},{sparse:true})
Pragmateek
  • 13,174
  • 9
  • 74
  • 108